What's the difference between docstrings and comments in python code?

A helpful tip for knowing when to use one vs the other.

What's the difference between docstrings and comments in python code?
Photo by Patrick Tomasso / Unsplash
💡
This is part of an on-going series in python basics. Check the coding 101 article tag index from time-to-time for more content.

Docstrings and comments ultimately serve a common purpose: they explain code. The big difference between them though is the intended audience.

Docstrings are typically written for users (and other developers) who want to understand how to use a piece of code (e.g. module, class, function, or method).

Here's an example of what a docstring would look like:

def some_function(input1, input2):
    """This is an example of a docstring.  It helps to
    communicate (typically in larger detail) a component 
    and describe to other developers what or how a 
    component would work."""
    print(input1)
    print(input2)

Notice the syntax and placement? Docstrings are wrapped in quotes (either """ or ''' and need to be placed immediately after an object definition.

Comments are more brief. Think of them like quick "note to self" items that a main developer wants to have top of mind. They're particularly helpful for reminding a developer about a specific piece of code logic.

Here's an example of what a comment could look like:

def calculate_area(length, width):
    # Calculate the area of a rectangle
    area = length * width  # Multiply length and width
    return area

Comments can be anywhere in code and are identified with the hash symbol (#).