开发者

The origin of using # as a comment in Python?

So I just had like this mental explosion dude! I was lo开发者_StackOverflow中文版oking 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?


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.


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!


"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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜