Ben Davis
Ben Davis

Reputation: 13810

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?

Upvotes: 8

Views: 10144

Answers (2)

I got the same error below with Flake8:

blank line at end of fileFlake8(W391)

Because I added more than one blank lines after the last code print(math.pi) as shown below:

1 import math
2
3 print(math.pi)
4
5

So, I added only one blank line after the last code print(math.pi) as shown below, then the error was solved:

1 import math
2
3 print(math.pi)
4

In addition, if you don't add one blank line after the last code print(math.pi) as shown below:

1 import math
2
3 print(math.pi)

Then, you get the error below:

no newline at end of fileFlake8(W292)

Upvotes: 0

Ben Davis
Ben Davis

Reputation: 13810

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.

Upvotes: 8

Related Questions