Search code examples
pythonlintpep8flake8pyflakes

Python flake8 py reporting W391 (no newline at end of file) incorrectly


W391 says that there should be one (and only one) blank line at the end of file. However, flake8 reports the error when there is at least one newline at the end of the file:

$ cat /tmp/test.py
def hello():
    print('hello')


hello()


$ hexdump -C /tmp/test.py
00000000  64 65 66 20 68 65 6c 6c  6f 28 29 3a 0a 20 20 20  |def hello():.   |
00000010  20 70 72 69 6e 74 28 27  68 65 6c 6c 6f 27 29 0a  | print('hello').|
00000020  0a 0a 68 65 6c 6c 6f 28  29 0a 0a                 |..hello()..|
0000002b

You can see above there is in fact one and only one blank line at the end of the file (0a is \n). However, when I run flake8, I get the W391 error:

$ flake8 /tmp/test.py
/tmp/test.py:6:1: W391 blank line at end of file

Why is that?


Solution

  • Apparently vim automatically adds a newline to every file, which fools me into thinking that last blank line isn't there. Over time this implicit newline confused me into thinking two newline characters at the end created one blank line.

    So, the warning is correct. There should be one and only one \n at the end of the file.