What is a Docstring?
And why should I add it to my code?
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.
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:
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!