Python comments: # vs. strings

后端 未结 3 1446
[愿得一人]
[愿得一人] 2020-12-14 01:38

Regarding the \"standard\" way to put comments inside Python source code:

def func():
    \"Func doc\"
    ... 
    \'TODO: fix this\'
    #badFu         


        
3条回答
  •  伪装坚强ぢ
    2020-12-14 02:09

    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.

提交回复
热议问题