Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The origin of using # as a comment in Python?

So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this:

#!/usr/bin/env python
# A regular comment

Which made me wonder, was # chosen as the symbol to start a comment because it would allow the python program to be invoked in a shell, like so:

./test.py

and then be ignored once the python interpreter was running?

like image 869
Kredns Avatar asked Dec 01 '22 11:12

Kredns


2 Answers

Yes.

Using # to start a comment is a convention followed by every major interpreted language designed to work on POSIX systems (i.e. not Windows).

It also dovetails nicely with the fact that the sequence "#!" at the beginning of a file is recognized by the OS to mean "run the command on this line" when you try to run the script file itself.

But mostly, it's the commonly accepted convention. If python didn't use # to start a comment, it would confuse a lot of people.

EDIT

Using "#" as a comment marker apparently pre-dates the "#!" hash-bang notation. "#!" was introduced by Dennis Ritchie betwen Unix 7 and 8, while languages that support # as a comment marker existed earlier. For example, the Bourne shell was already the default when Version 7 Unix was introduced.

Therefore, the convention of using "#" as a comment marker probably influenced the choice of "#!" as the command line marker, and not the other way around.

like image 62
tylerl Avatar answered Dec 04 '22 05:12

tylerl


Using # for comments was happening before Python came around. The shebang (#!/usr/bin/env python) convention is almost as old as UNIX itself. The two are intertwined for many interpreted (aka shell) languages.

Might as well study up on the history of the shebang!

like image 45
jathanism Avatar answered Dec 04 '22 04:12

jathanism