How to Easily Write Docstrings in Python Without a Headache (Using VSCode)
Writing docstrings in Python can feel like a chore — especially with the odd formatting involving triple quotes, >>>
signs, and parameter blocks. But clear, standardized docstrings are critical for both readability and maintainability.
If you’re using VSCode (Visual Studio Code), you’re in luck. With a few extensions and configurations, you can make writing professional, PEP 257-compliant docstrings painless.
Why Docstrings Matter
- They help you remember why you wrote something.
- They help others understand your code quickly.
- Tools like Sphinx, pdoc, and PyDoc use them to generate documentation automatically.
- They make your codebase feel like it's actually maintained.
Docstring Formats
There are several commonly used formats:
- reStructuredText (reST) - Recommended for Sphinx.
- Google-style
- NumPy-style
Here’s an example of each:
reST Format
def add(x, y):
"""
Add two numbers.
:param x: First number
:type x: int
:param y: Second number
:type y: int
:return: Sum of x and y
:rtype: int
"""
return x + y
Google-style
def add(x, y):
"""
Add two numbers.
Args:
x (int): First number.
y (int): Second number.
Returns:
int: Sum of x and y.
"""
return x + y
NumPy-style
def add(x, y):
"""
Add two numbers.
Parameters
----------
x : int
First number
y : int
Second number
Returns
-------
int
Sum of x and y
"""
return x + y
Setting Up VSCode to Write Docstrings Easily
-
Install the right extensions:
- Python (ms-python.python)
- autoDocstring (njpwerner.autodocstring)
-
Enable Auto Docstring Generator:
- Open VSCode Command Palette (
Ctrl+Shift+P
orCmd+Shift+P
) - Select
Preferences: Open Settings (UI)
- Search for
autoDocstring.docstringFormat
and choosegoogle
,numpy
, orsphinx
- Open VSCode Command Palette (
-
Use the Docstring Shortcut:
- Place your cursor inside a function.
- Press
Ctrl+Shift+2
(or runGenerate Docstring
command). - VSCode will auto-generate a docstring stub based on the function’s signature.
Pro Tips
- Use type hints in your function definitions — the generator will include them automatically.
- Combine with Pylance and mypy for type checking and linting.
- Document edge cases and side effects — good docstrings are not just about parameters.
- Keep your docstrings concise but informative.
Conclusion
Writing docstrings doesn’t have to feel like medieval torture. With VSCode and autoDocstring, it's almost fun — and definitely a productivity booster.
Keep it short. Keep it clear. Keep it consistent.
Happy coding!