34

As far as I know in unix it's a good practice to always have blank line at the end of file - or to put it in other words: every line should end with \n.

While checking my python code with PEP8 I noticed that it also states that there should be \n at end of file:

W292 no newline at end of file
    JCR: The last line should have a newline.

What's strange, it conflicts with W391:

W391 blank line at end of file
    JCR: Trailing blank lines are superfluous.

    Okay: spam(1)
    W391: spam(1)\n

How it should be? Should I have blank line at the end of file or not?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
seler
  • 8,803
  • 4
  • 41
  • 54
  • 4
    Which PEP 8 are you referring to? The [official page](http://www.python.org/dev/peps/pep-0008/) doesn't mention this at all. – Tim Pietzcker Mar 19 '12 at 10:02
  • the output is from ``pep8 --show-pep8`` installedy from PYPI. – seler Mar 19 '12 at 10:42
  • @TimPietzcker good point, I can't see it in the original document. It looks like `pep8` module (`pycodestyle` nowadays) took monopoly on style from the original document. – greatvovan Jan 31 '23 at 23:44

4 Answers4

42

W391 is a blank line, that is, two consecutive \ns. There is no conflict.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    What about example shown in pep? It says there should be no ``\n`` at end. I guess what you mean is ``spam(1)\n
    \n``.
    – seler Mar 19 '12 at 10:44
  • 17
    It looks linke VIM adds ``\n`` at end of each file without actually going to the next line. Neat! – seler Mar 30 '12 at 13:10
17

This is what W391 is talking about:

print 'last line'


This is wrong according to W292:

print 'last line'

What is correct is:

print 'last line'

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Hrm.. when I have the last version, which displays as you have it in vim, and via cat, I get a W391 warning from syntastic. I don't get the warning when I have the second example. Is that a bug in syntastic? – naught101 Feb 09 '15 at 00:24
  • 3
    @naught101 Vim adds the final newline behind the scenes. In this instance, Vim is tricking you. There are plugins to tell Vim not to add the final newline if you prefer. – Nick Sloan Apr 22 '15 at 02:46
3

In Windows '\n' is the separator between lines, but in Linux '\n' is the ending sign on any line. Vim did nothing wrong to add '\n' to the end of lines in Linux platform but following OS definition.

gmauch
  • 1,316
  • 4
  • 25
  • 39
jeffzh
  • 31
  • 3
0

W292 occurs if you don't add one blank line after the last code as shown below:

1 import math
2
3 print(math.pi) # The last code

W391 occurs if you add more than one blank lines after the last code as shown below:

1 import math
2
3 print(math.pi) # The last code
4
5

So to avoid W292 and W391, you should add only one blank line after the last code as shown below:

1 import math
2
3 print(math.pi) # The last code
4
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129