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

Ben*_*vis 8 python lint pep8 pyflakes flake8

W391 规定文件末尾应该有一个(且只有一个)空行。然而,当文件末尾至少有一个换行符时,flake8 会报告错误:

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


hello()


Run Code Online (Sandbox Code Playgroud)
$ 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
Run Code Online (Sandbox Code Playgroud)

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

$ flake8 /tmp/test.py
/tmp/test.py:6:1: W391 blank line at end of file
Run Code Online (Sandbox Code Playgroud)

这是为什么?

Ben*_*vis 9

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

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