views:

219

answers:

4

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?

+1  A: 

"All the rest of the line after character X" is clearly the handiest way to do comments if you have an X available (C++ had to use two characters, //, for the purpose, to offer an alternative to C's clunky PL/I-inspired '/' ... '/' "brackets").

Almost all printable Ascii characters can be used for other purposes in Python -- if the choice is between # and ?, with the first already being familiar from its use in sh, bash, tcl, perl, awk, ... -- it's not a very hard choice, is it? The handiness of hashbang is just a vig.

Alex Martelli
+12  A: 

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.

tylerl
Your edit is "where it's at". :)
ΤΖΩΤΖΙΟΥ
+6  A: 

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!

jathanism
No, the shebang is not almost as old as Unix itself. Late twenties does not equal forties, sorry :)
ΤΖΩΤΖΙΟΥ
A: 

Very good, you are correct.

This is known as the shebang or hash-bang. I suppose a scripting language could use any comment character it liked and allow #! on the first line as a comment, but it does seem easier to just make # be the comment character...

DigitalRoss
Mainly because the interpreter (i.e.: python) receives the full script as its input, including the shebang line, so if it is not a comment a special case should have been considered.
dtmilano