Python flake8 py 错误地报告 W391(文件末尾没有换行符)

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

W391 说文件末尾应该有一个(而且只有一个)空行。但是flake8在文件末尾至少有一个换行符的时候报错:

$ 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

你可以看到上面的文件末尾实际上只有一个空行(0a\n)。但是,当我 运行 flake8 时,出现 W391 错误:

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

这是为什么?

显然 vim 会自动为每个文件添加一个换行符,这让我误以为最后一个空行不存在。随着时间的推移,这个隐含的换行符让我误以为末尾的两个换行符创建了一个空行。

所以,警告是正确的。文件末尾应该只有一个\n