W391 blank line at end of file python что делать

Comments

ghost commented Dec 31, 2014

Seems like a contradiction, fixing W391 introduces W292

Maybe there is an issue with the way I resolved W391

The text was updated successfully, but these errors were encountered:

sigmavirus24 commented Dec 31, 2014

A newline at the end of a file does not mean that there needs to be an empty line. Your editor may not show this to you but the raw bytes would look like:

If you don’t have the last \n there then you will see W391. You seem to be doing

Edited to fix the last example.

IanLee1521 commented Jan 3, 2015

Could you provide some sample code where this is an issue? Thanks.

jkterry1 commented Mar 15, 2018

Hey, I seem to be having this issue as well, with this sample code:

FichteFoll commented Mar 15, 2018 •

Since this error is highly whitespace-sensitive, I don’t think it can be reproduced with simple code blocks as those are stripped. Please upload files.

That said, I suspect that the initial problem was that the end of the file looked as follows:

Note that the last line here is not empty but has 4 spaces. This should raise W391. It was then attempted to fix the error by removing the last newline, but that left the four spaces in the now last line, which caused W292 to be raised.

hoylemd commented Mar 16, 2018 •

As a workaround in the meantime, I have a bit in my editor(vim) config(.vimrc) that strips trailing whitespace whenever a buffer is saved. That might help you (@justinkterry) in the short term, if you use vim and are ok with your editor cleaning whitespace up for you:

bsmoliak commented Jan 4, 2019

W391 appears to supercede W292.

Seems like W292 should be raised first.

codypiersall commented Jan 16, 2019

Hmmm, for what it’s worth, it seems like Vim inserts the newline at the end of the file, but it doesn’t look like there is a newline. I wonder if this is what was happening with the OP?

kierun commented Mar 7, 2019

This is the file I use:

The last line does have a [W292] warning on it. Flake8 passes fine.

Running hexdump, get:

This is what I see on screen:

OS: Centos (7.6.1810), neovim (0.3.2), and neovim-qt (master)…

FichteFoll commented Mar 7, 2019

What happens when you run pycodestyle sanitise.py from the command line? This could be a problem in the vim intergation.

kierun commented Mar 7, 2019

What happens when you run pycodestyle sanitise.py from the command line? This could be a problem in the vim intergation.

Источник

blank line at end of file #40

Comments

DXist commented Nov 2, 2011

The text was updated successfully, but these errors were encountered:

florentx commented Mar 25, 2012

pep8.py correctly detects ‘\n\n’ at end of file with warning W391.
It does not find any error if the file ends with ‘\n’ only.
I don’t see any misbehaviour here.

DXist commented Mar 26, 2012

I’ve installed pep8 0.7.0 from PyPI.

So pep8 from PyPI still has this problem

florentx commented Mar 26, 2012

You did not do the right test.

DXist commented Mar 26, 2012

Right. So I close the issue.

techtonik commented May 22, 2012

DXist commented May 22, 2012

techtonik commented May 22, 2012

Actually it is more typing, because without \n\n in Vim you can not just go to the end of file an press enter. You enter will at the start of the last line. It suxx that PEP8 validator forces everybody to this annoyance.

DXist commented May 22, 2012

You can type o command to start new line after you go to the end of file

Читайте также:  Как украсить свадебные свечи

techtonik commented May 22, 2012

Yes, I can, but I forget all the time.

techtonik commented May 22, 2012

And still PEP8 doesn’t require that files should not end with blank lines.

florentx commented May 23, 2012

I understand each developer has its habits.
I use Vim, and I regularly check my code with pep8.py. I don’t see a problem with the default settings.

techtonik commented May 23, 2012

Of course developers have habits. Why make it more harder for other people if doesn’t make any difference for yourself? Will the presence of \n\n endspace instead of \n bug you more than absence of \n\n bugs me, DXist and other people? You still can apply your rule to count(‘\n’) > 2

jorgesumle commented Sep 6, 2016

The-Compiler commented Sep 7, 2016

@jorgesumle So turn it off? I find it useful.

techtonik commented Sep 7, 2016

I remember there was some unix story about those linefeeds at the end of file, so this must be some unix kludge from the past and now is a cargo ritual. =)

DXist commented Sep 7, 2016 •

So the last new line is important for diff tools (including Github) and must have for C/C++. I guess early C development toolchain incorrectly handled the last line without line terminator symbols.

I think new line at the end of file is a part of best practices and I dislike editors/IDEs that don’t put last new line by default. Rituals support common and clear coding style.

Источник

W391 blank line at end of file python что делать

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.

Источник

Русские Блоги

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()’

Интеллектуальная рекомендация

JavaParser: генерация кода Java

Linux выполняет ошибку команд Java: не могу найти или не удалось загрузить основной класс

проблема: Используйте Javac для Compile Test.java на Linux, но используйте Java для запуска Test.Class Tips: Ошибка: Не удается найти или не удалось загрузить основной класс решение: редактировать/etc.

Excel отозвать защиту работы (забыл пароль)

Решите проблему сбоя ноутбука jupyter и измените путь по умолчанию для ноутбука jupyter

Некоторое время назад anaconda на компьютере по умолчанию была обновлена ​​до python3.6, и некоторые часто используемые модули необходимо переустановить. Кроме того, есть такие проблемы, как невозможн.

Источник

PEP8: конфликт между W292 и W391

Проверяя свой код python с помощью PEP8, я заметил, что он также утверждает, что в конце файла должно быть \n :

Что странно, он конфликтует с W391:

Как это должно быть? Должен ли я иметь пустую строку в конце файла или нет?

3 ответа

В /tmp/spam.py году : n = 69 if n == True: print ‘potato’ утилита pep8 жалуется на это условно: wim@SDFA100461C:/tmp$ pep8 spam.py spam.py:3:6: E712 comparison to True should be ‘if cond is True:’ or ‘if cond:’ первое предложение-wrong/worse в соответствии с самим pep8 второе предложение изменяет.

W391-это пустая строка, то есть две последовательные \n с. Нет никакого конфликта.

Это то, о чем говорит W391:

Это неправильно согласно W292:

Что правильно, так это:

Похожие вопросы:

Поиск ответа в списке рассылки Pylint не приносит никаких интересных результатов. Pylint, как известно, очень настраиваем, поэтому я думаю, что это должно быть возможно. Причина, по которой я.

Я хочу, чтобы меня предупреждали, когда я пишу код python, который нарушает pep8 в Редакторе eclipse. Насколько я вижу, настройки показывают, что он должен работать под управлением pep8. (Ниже.

Вот какой-то код: foo = Bears Lions, Tigers and %(foo)s % locals() Мой Линтер PEP8 (SublimeLinter) жалуется на это, потому что foo-это unreferenced. Мой вопрос заключается в том,следует ли PEP8.

В /tmp/spam.py году : n = 69 if n == True: print ‘potato’ утилита pep8 жалуется на это условно: wim@SDFA100461C:/tmp$ pep8 spam.py spam.py:3:6: E712 comparison to True should be ‘if cond is True:’.

Как известно большинству людей, использующих PyCharm, PyCharm имеет встроенный PEP8 ‘rule book’, который (если вы включите его) проверяет ваш код, видит, есть ли в нем какие-либо несоответствия в.

Проект, над которым я работаю, запускает проверку линтинга перед проверкой сборки. Линтер, помимо всего прочего, проверяет соответствие PEP8. У меня есть строка base64 длиной около 5000 символов.

Согласно стандартам PEP, отступы должны стоять перед двоичными операторами. Кроме того, многострочные условия должны быть заключены в круглые скобки, чтобы избежать использования обратной косой.

Источник

Читайте также:  Желтая шапка мужская с чем носить
Обучающий проект