PEP8 "No newline at end of file"

12.6k Views Asked by At

I'm trying to understand the error below from Flake8:

no newline at end of fileFlake8(W292)

This is my code below:

if __name__ == "__main__":
    app.run(
        host=os.environ.get("IP", "0.0.0.0"),
        port=int(os.environ.get("PORT", "5000")),
        debug=False)

And, the error is pointing to the last line below:

debug=False

Can someone help explain to me why I'm getting this invalid error and offer a solution to solve it. Thanks

2

There are 2 best solutions below

1
Stephen C On

It means exactly what it says. There is no recognizable newline at the end of the file. The last character is the ) ... or maybe a TAB, or SPACE, or a line terminator for a different platform.

Solution: open the file in an editor, add a newline at the end, save and close the file.


I've tried that, I had a new line after it and I get "blank line contains whitespace" error.

So what you had was a line consisting of white space (SPACE or TAB characters) followed by a newline. Use your editor to get rid of that line.

The style checker wants the last line of the file to end with the newline character, and to have no trailing whitespace on that line.

1
Super Kai - Kazuya Ito On

I got the same error below when using Flake8:

no newline at end of fileFlake8(W292)

Because I didn't add one blank line after the last code print(math.pi) as shown below:

1 import math
2
3 print(math.pi)

So, I added 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

Actually, I saw PEP 8 but I could not find why to add one blank line after the last code but the error below also occurred in the same situation when using Pylint:

Final newline missingPylint(C0304:missing-final-newline)

So, I think that adding one blank line after the last code is recommanded in Python even though I don't know the reason.

In addition, if you add 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

Then, you get the errors below with Flake8 and Pylint respectively:

blank line at end of fileFlake8(W391)

Trailing newlinesPylint(C0305:trailing-newlines)