Python comments: # vs. strings

Question:

Regarding the “standard” way to put comments inside Python source code:

def func():
    "Func doc"
    ... <code>
    'TODO: fix this'
    #badFunc()
    ... <more code>

def func():
    "Func doc"
    ... <code>
    #TODO: fix this
    #badFunc()
    ... <more code>

I prefer to write general comments as strings instead of prefixing #’s.
The official Python style guide doesn’t mention using strings as comments (If I didn’t miss it while reading it).

I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don’t do anything.

Are there disadvantages in doing this?

Asked By: bigmonachus

||

Answers:

I think that only the first string literal in a definition (or class) is “special”, i.e. gets stored by the interpreter into the defined object’s (or class’) docstring.

Any other string literals you place in the code will, at the worst, mean the interpreter will build the string value at run-time, and then just throw it away. This means that doing “comments” by littering the code with string constants might cost, performance-wise.

Of course, I have not benchmarked this, and also don’t know the Python interpreter well enough to say for sure.

Answered By: unwind

The disadvantage, of course, is that someone else reading it will find that the code strings and comment strings are interleaved, which could be confusing.

Answered By: Swaroop C H

Don’t misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.

Note that docstrings are documentation, and documentation and comments are two different things!

  • Documentation is important to understand what the code does.
  • Comments explain how the code does it.

Documentation is read by people who use your code, comments by people who want to understand your code, e.g. to maintain it.

Using strings for commentation has the following (potential) disadvantages:

  • It confuses people who don’t know that the string does nothing.
  • Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read.
  • It might affect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so it’s definitively cheaper)

Most important for Python programmers: It is not pythonic:

There should be one—and preferably only one—obvious way to do it.

Stick to the standards, use comments.

Answered By: Ferdinand Beyer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.