I think writing comments in python is grossly under-utilized and under appreciated. Many programmers say that your code should always be readable, thus they do not need comments. Others say that you don't need comments because you should have tests that show what the function is doing. While I think both are valid, comments are still necessary.
Why Comments are Needed
Comments allow you to explain everything at a higher, deeper level. It gives other programmers who need to work on your code context to what the function they're working on is supposed to do. It also allows these programmers to refactor any poorly written code you wrote because they'll know for sure what the function is supposed to do. It prevents the "hacky" fixes and allows people to develop for what the function needs to do.
They also allow you to have a deeper knowledge of what you need to do to write your function. If you write the comment before you write your function, then you don't get held up by uncertainty when writing it in python code.
It allows you to develop an api for other programmers to use. An api without comments is like buying a do-it-yourself kit without instructions. Yes, other programmers can probably figure out what to do eventually, but they won't be happy doing it if they have to stumble over everything.
Why we don't put comments
- We are lazy
- Our current code isn't commented, so don't have the will to start
- We don't feel like we have time
I've certainly experienced all of these reasons. The first step is to realize you have a problem. The second step is to start writing comments.
How to write comments
Docstrings
The best way to write comments in python is to use docstrings. Docstrings allow programmers to see the comments of a function while running python by doing `help(<function_name>)`. They are also conveniently always right under the function declaration, which is very helpful for programmers looking for function comments. This is how to write a docstring:
def function_name(param1, param2):
"""your_comments
...
"""
<rest_of_your_function>
As you can see, it's a pretty standard python comment, except that it is always placed right underneath the python declaration. If it's not placed there, then it's not a docstring.
Comment Design Patterns
We want to provide other programmers with the most understandable, standardized comments possible, so lets take a look at what these comments should have and where they should have them.
def function_name(param1, param2):
"""<What_Your_Function_Returns>
<More_In_Depth_Of_What_Your_Function_Does_and_Returns>
<Your_Function_API>
<Examples_Of_How_To_Call_Your_Function_And_What_It_Returns>
<And_Special_Case_Examples_Like_Errors>
<Anything_Extra_You_Want_To_Add>
"""