What is a Docstring?

And why should I add it to my code?

3 min readSep 15, 2021


Photo by Tara Evans on Unsplash

Hello friends! I am in week 3 of my learning journey with Python. I am continuing to love it, and let me just emphasize to any other newbie software engineers that learning your second and third language are significantly easier than learning your first one.

Something new that I came across this week that I hadn’t yet encountered in Ruby or JavaScript was this little thing called docstrings. Today, I’m going to break down what the hell a docstring is, why you should add them to your code, and how to do just that.

What is a Docstring?

Docstring is short for documentation string, and it’s exactly what it sounds like! It’s a string literal that is used to help explain a specific line of code. For example, let’s say I’m using the len() function in Python:

Do you see the description above the len() function while I’m typing out the code? That is the docstring found in the actual Python documentation to help explain the len() function if you need a little reminder. But, what’s even cooler is you can create your own docstrings for the functions you build out in your Python projects. Check it out below!

Implementing Docstrings into Your Code

The symbol for implementing a docstring is quite simple: three sets of quotation marks:

"""Inside these three quotations is my docstring."""

Pretty easy huh? When you implement it in your code, you want to put it right after you define the function. Let’s say you want to write a function called sum that will add two numbers together. You would add the docstring like so:

Now, when I call on the function, here’s what appears:

Pretty neat!

If, for some reason, you want to access that string, it is within the __doc__ object, and you can access it like so:

***Pro-tip: Make sure you put two underscores on each side of the “doc”…learned that the hard way!

Why are docstrings important?

Docstrings may seem like a silly and somewhat unnecessary tool for small projects, but once you start building out big applications it can be a really big game changer. If you wrote a function you want to call on that’s 200 lines of code away, rather than scrolling through and trying to find how it works, the docstring will do the work for you and demonstrate not only what the function does, but what parameters to include.

And that’s it! A simple addition to your Python code that will make your life a lot easier when handling large amounts of code. Check out the official documentation about Python docstrings here. Happy coding!




Blaire is a musical theatre performer who also moonlights as a full-stack software engineer. https://www.linkedin.com/in/blaire-baker