niamulbengali
niamulbengali

Reputation: 275

Why does IDLE add a newline after my code?

On my saving a .py file, IDLE (Python 3.9 x64) will add a newline after the code itself. It is setting off my OCD while making me curious. For instance, take this entirely original last line of a program while coding:

print("Hello, world!")

Yet, when saved, it becomes:

print("Hello, world!")
# ghost line!

What is the significance of that extra line—can I turn it off?

Upvotes: 2

Views: 500

Answers (2)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19174

IDLE has made sure that a file being saved ends with a newline ('\n') since the first commit in 2000. I believe that at one time the Python compiler required that every line, including the last, be complete, ending with a newline. It may be more lax now, under some circumstances, but I am not sure. There may be other things one does with a file that could require the proper ending.

Ghosts do not exist, and neither does the ghost line. A line of 0 characters is not really a line. The cursor at the left margin after the last line is ready to start a new line.

Upvotes: 1

Richa Bhuwania
Richa Bhuwania

Reputation: 180

It is the best practice of Python to have an extra line at the end of the code. If you explicitly go and delete the last line, then it won't be there. But, my suggestion would be to keep it. It's always better to follow best practices.

Upvotes: 1

Related Questions