Python script should end with new line or not ? Pylint contradicting itself?

喜夏-厌秋 提交于 2021-02-07 12:22:28

问题


I am new to Pylint, and when I run it against my script, I get this output:

C: 50, 0: Trailing newlines (trailing-newlines)

Here, Pylint is saying that it is bad to have a final newline.

I like to have a new line at the end of my scripts, so I thought I would disable this warning. I did some google web searching and found this: http://pylint-messages.wikidot.com/messages:c0304

C0304 Message

Final newline missing

Description

Used when a Python source file has no line end character(s) on its last line.

This message belongs to the format checker. Explanation

While Python interpreters typically do not require line end character(s) on the last line, other programs processing Python source files may do, and it is simply good practice to have it. This is confirmed in Python docs: Line Structure which states that a physical line is ended by the respective line end character(s) of the platform.

Here, Pylint is saying that it is bad to miss the final newline.

(A) What is the correct view ? (B) How do I disable the check for the final new line ?

{{ EDIT : It turns out that this is not an issue with Pylint ; It is an issue with vim , which adds eol automatically : VIM Disable Automatic Newline At End Of File }}


回答1:


The pylint warning you are getting is complaining that you have multiple trailing newlines. The C0304 message occurs when there is no trailing newline at all.

These messages are not contradictory they indicate different problems.

The reason you need at least one newline is that historically some tools have problems if the file ends and the last line has text on it but does not have a newline at the end of the file. Badly written tools can miss processing that last partial line, or even worse can read random memory beyond the last line (though that is unlikely to happen with tools written in Python it can happen with tools written in C).

So you must ensure there is a newline terminating the last non-blank line.

But you don't want any completely blank lines at the end of the file either. They won't actually produce bugs but they're untidy. So delete any blank lines and you should be fine.




回答2:


C0304 Final newline missing is the error occures when a Python source file has no line end character(s) on its last line.

I am telling you the way to disables the pylint warring.

To disable the warning you can simple add the below line in your .py file, generally good practice to add before the imports.

# disabling:
# C0304: Trailing newlines (trailing-newlines)
# pylint: disable=C0304

OR You can create a configuration file ~/.pylintrc this allows you to ignore warnings you don't care about.



来源:https://stackoverflow.com/questions/43491498/python-script-should-end-with-new-line-or-not-pylint-contradicting-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!