When you’re writing Python code, you want it to be clear and easy to understand —not just for yourself but for anyone else who might work with your code later.
That’s where docstrings come in. They’re like a roadmap for your code.
With just a few lines, you can clearly explain what your functions, classes, and modules do, helping both you and anyone else who interacts with your code. Adding docstrings makes your code easier to read, maintain, and even automate!
Ready to make your Python code easier for you (and everyone else) to understand?
Let’s dive into the world of docstrings and level up your Python skills.
Sidenote: If you find any of this confusing, or simply want a deep dive into Python, check out Andrei's Python Coding course taken by 200,000+ people:
It’ll take you from an absolute beginner and teach you everything you need to be hired ASAP.
Alternatively, if you're already pretty good at Python and want to build some interesting and useful projects, why not check out my course on Python Automation:
It'll show you how to automate all of the boring or repetitive tasks in you life - and makes for some pretty stand out portfolio projects!
With that out of the way, let's get into this 5-minute tutorial!
There are two main ways to explain what your code is doing:
They each have a different purpose, so let’s quickly break them down.
Comments are like little notes you leave for yourself (or another developer) in the code.
They’re informal and super useful while you’re working on a specific section or debugging. But here’s the catch: comments stay hidden in the source code and won’t show up outside of it.
For example:
# This is a comment explaining a specific line of code
result = x + y
This comment helps clarify what’s happening in the line of code that follows, but it won’t be visible outside the source code.
Sidenote: If you want to learn more about comments, check out my guide here.
Docstrings are a step up from comments.
Think of them as mini-explanations that stick with your functions, classes, or modules. They live inside your code, but they’re also accessible through Python's help()
function, making them perfect for creating formal documentation.
For example
def add_numbers(x, y):
"""
This function takes two numbers and returns their sum.
"""
return x + y
Unlike comments, docstrings can be used by anyone interacting with your code—even without opening the source files! They’re meant to help other developers (and future you) understand what the code is supposed to do.
You might be thinking, “Why bother with docstrings when comments do the job?”
The key difference lies in how they’re used. Comments are great while you’re writing or debugging, but they don’t help anyone who isn’t looking directly at your code. That’s where docstrings step in.
Docstrings don’t just live in the code - they can be pulled out and used as formal documentation, making it easy for others to understand your code without even opening the file. It’s like leaving behind a user manual right inside your Python scripts.
Here’s why well-written docstrings are so useful:
For example, if you want to access the docstring of a function, you can use Python’s help()
function:
help(add_numbers)
Here’s what you’d see:
Help on function add_numbers in module __main__:
add_numbers(x, y)
This function takes two numbers and returns their sum.
With docstrings, you’re making your code not only functional but also easy for others to understand—whether they’re running it or maintaining it.
Let’s compare docstrings to comments so you can see the difference in action.
Here’s a function with a simple comment:
# This function prints a greeting message to the user
def greet(name):
print(f"Hello, {name}!")
The comment tells you what the function does, but it’s only useful if you’re looking at the source code. If someone else wanted to figure out what this function does without diving into the code, they’d be stuck. Now, let’s add a docstring instead:
def greet(name):
"""
This function takes a name and prints a greeting message.
"""
print(f"Hello, {name}!")
Not only does this docstring explain the function inside the code, but you can also access it using Python’s built-in help()
function. Let’s try it out:
help(greet)
The output will be:
Help on function greet in module __main__:
greet(name)
This function takes a name as input and prints a greeting message.
With a docstring, your function becomes self-explanatory and accessible to anyone—whether they’re reading your code or using help()
to learn more about it.
This is a huge benefit, especially if you’re working on a project with other developers or planning to share your code with others.
Now that you’ve seen how docstrings work, let’s talk about how to write them the right way. Python has specific guidelines for writing docstrings, laid out in PEP 257.
These guidelines help make sure your docstrings are easy to read and consistent, no matter who’s reading or using your code.
If your function or method is straightforward, you can use a single-line docstring. These docstrings are perfect for quick, to-the-point explanations. You’ll often use them in simple scripts or when automating smaller tasks.
Here’s how they look:
def is_even(number):
"""Return True if the number is even."""
return number % 2 == 0
Notice that the docstring is on one line and there’s no period at the end. That’s standard practice unless your description has more than one sentence.
For more complex functions, classes, or modules, a single line won’t cut it. That’s when you’ll use a multi-line docstring. These are ideal when you need to provide more context, like explaining parameters or how the function works.
Here’s the format to follow:
Here’s an example for an automation script:
def backup_files(source, destination):
"""
Copy all files from the source to the destination directory.
Parameters:
source (str): The path to the source directory.
destination (str): The path to the destination directory.
This function automates the process of creating a backup of files,
ensuring all contents from the source are replicated in the destination.
"""
# Automation code to copy files here
Multi-line docstrings are especially helpful when you’re documenting Python automation scripts that involve multiple steps or parameters.
Writing effective docstrings isn’t just about documenting your code—it’s about making it clear and helpful for you and anyone else who might need to understand or use it.
Let’s go over some best practices that’ll help you write docstrings that save time and make your code easier to work with.
The main goal of a docstring is clarity. You want anyone reading it to understand exactly what your function, class, or module does without overcomplicating things. Avoid jargon unless it’s absolutely necessary.
For example:
def send_email(recipient, subject, body):
"""
Send an email to the specified recipient.
Parameters:
recipient (str): The email address of the recipient.
subject (str): The subject of the email.
body (str): The body content of the email.
"""
# Code to send the email
This docstring is short, to the point, and includes all the key details about the function. No fluff, just clear information that will help you or someone else quickly grasp what the function does.
Formatting may seem like a small detail, but it makes a huge difference when you’re reading or generating documentation. Following PEP 257 ensures your docstrings are consistent, easy to read, and professional. Poorly formatted docstrings can be hard to read, making your documentation messy and harder to follow.
For multi-line docstrings:
Here’s an example of poor formatting:
def get_data():
"""This function retrieves data from the database
and returns it as a dictionary
"""
# Code to get data
And here’s the proper way to format it:
def get_data():
"""
Retrieve data from the database and return it as a dictionary.
This function connects to the database, queries for the data,
and structures it as a Python dictionary for easy access.
"""
# Code to get data
Why does this matter?
Proper formatting keeps your docstrings readable and helps tools like Sphinx or PyDoc easily parse them into professional-looking documentation.
It also ensures consistency across your projects, making it easier for other developers to collaborate on your code or use your work as a reference.
Don’t just say what the function does—explain why it matters. This adds context and helps others (or your future self) understand how a function fits into the bigger picture.
For example:
def send_reminder(email, event):
"""
Send a reminder email for an upcoming event.
Parameters:
email (str): The recipient’s email address.
event (str): The name of the event for which the reminder is being sent.
This function automates the process of sending reminder emails,
making sure users are notified ahead of important events.
"""
# Code to send the reminder
This way, anyone reading your code understands not just what it does, but why it’s important.
Your code will change over time, and your docstrings need to change with it.
Imagine trying to debug a function, only to find that the docstring describes an old version of the code - it’s frustrating and can slow down development. Keeping your docstrings up to date ensures your documentation is reliable and helps prevent errors.
In automation scripts, where functions often interact with external systems or perform repetitive tasks, docstrings are even more critical.
A well-documented script not only helps others understand what’s happening but also allows you to revisit the script later without needing to re-figure out how everything works.
For example:
def system_health_check():
"""
Run a health check on system resources (CPU, memory, disk space).
This function automates the process of checking system resources
and logs the data for future analysis.
"""
# Automation code for health check
When you’re automating tasks like system health checks, docstrings make it clear what the script is doing and why.
This level of documentation ensures that anyone running the script knows what to expect, reducing confusion and errors.
So far, we’ve covered docstrings for individual functions and classes, but you can use them on a larger scale too. Docstrings are essential for documenting entire modules and packages, especially when you’re working on larger projects or automation scripts split across multiple files.
Clear documentation helps anyone understand the big picture of what your code is doing without diving into each function.
When you write a Python module or package, adding a docstring at the top of the file gives others (or future-you) a quick overview of what the module does.
This is particularly important in automation scripts, where different modules might handle specific tasks, and it’s not always obvious how everything fits together just from looking at the code.
Here’s how you’d document a module:
"""
This module automates the process of monitoring system health and reporting
resource usage such as CPU, memory, and disk space.
Functions:
- check_cpu_usage: Checks the current CPU usage.
- check_memory_usage: Checks the current memory usage.
- generate_report: Generates a report of system health data.
"""
Why does this matter?
By including this high-level description, anyone reading the module can quickly understand what it’s automating and how its functions work together.
This is especially helpful in larger projects where digging through individual functions to figure out the module’s purpose would be time-consuming.
When documenting a class, you’re not just explaining a single function - you’re describing the purpose of the class itself, along with its attributes and methods. This kind of documentation is essential in automation projects, where classes often manage complex tasks or interact with external systems.
Here’s how you can structure a class docstring:
class FileBackup:
"""
A class used to automate the backup of files from one directory to another.
Attributes:
source (str): The source directory from which files are backed up.
destination (str): The destination directory where files are copied.
Methods:
backup(): Copies files from source to destination.
"""
def __init__(self, source, destination):
self.source = source
self.destination = destination
def backup(self):
# Code to backup files
Why is this helpful?
By clearly describing the class attributes and methods, you make it much easier for others (and yourself) to understand how the class works and how it fits into the larger project.
This becomes especially important in automation projects where classes may be responsible for managing multiple steps, like backing up files or running system checks.
Writing great docstrings is just the first step, but wouldn’t it be awesome if you could turn them into professional-looking documentation with little extra effort? That’s exactly what docstring tools and generators are for.
These tools take the docstrings you’ve written and convert them into clean, readable documentation, ready to share with others or use in your projects. Let’s explore two popular options you can use to make your documentation process easier.
Sphinx is one of the most popular tools in the Python community for generating documentation from code. It can turn your docstrings into well-formatted HTML, PDF, or even ePub documents, making it perfect for larger projects or automation scripts that need thorough documentation.
Here’s how it works:
Sphinx is a game-changer because it saves you time and ensures your documentation is professional and easy to navigate. If you’re working on a larger project - especially one that involves automation scripts that others may need to modify - having clear, structured documentation is invaluable.
Here’s an example of how you might document an automation script that backs up files between servers:
def upload_files_to_s3(file_paths, bucket_name, access_key, secret_key):
"""
Uploads a list of files to an Amazon S3 bucket.
Parameters:
file_paths (list): A list of file paths to be uploaded.
bucket_name (str): The name of the S3 bucket.
access_key (str): AWS access key for authentication.
secret_key (str): AWS secret key for authentication.
This function automates the process of uploading files to an AWS S3 bucket
for storage or distribution. It uses the AWS SDK to manage authentication
and file transfer.
"""
# Code to upload files to S3
With Sphinx, this docstring can be transformed into a full set of HTML documentation, so anyone on your team can understand the script without having to read through the code.
Install Sphinx using pip:
pip install sphinx
Then, set up Sphinx in your project:
sphinx-quickstart
Next, you need to configure Sphinx to use your docstrings by enabling the autodoc
extension in the conf.py
file:
extensions = ['sphinx.ext.autodoc']
Finally, run the documentation build process:
make html
Once you’ve done this, you’ll have a full set of professional-grade HTML documentation generated from the docstrings in your code. For Python automation projects, this is especially useful when you’re sharing scripts or working with a team.
If you don’t need all the power and flexibility of Sphinx, PyDoc is a built-in tool that generates basic documentation directly from your docstrings.
It’s great for smaller projects or when you want to quickly check how your docstrings look without setting up a full documentation environment.
To generate documentation with PyDoc, just run this command:
pydoc my_module
PyDoc will generate a simple text-based version of your documentation, which can be viewed locally or served via a web browser. It’s perfect for quickly previewing docstrings and ensuring everything is in order without going through the hassle of setting up a full Sphinx project.
Why use PyDoc? If you’re working on smaller scripts or just want to see how your docstrings look in a documentation format, PyDoc gets the job done quickly. It’s built into Python, so there’s no extra setup required.
Hopefully by now you’ve got a solid understanding of what docstrings are, how to write them, and why they’re so valuable - especially when you’re working on Python automation.
With clear, well-structured docstrings, you’ll make your code easier to maintain, share, and scale. Whether you’re automating tasks or building more complex projects, good documentation will save you and others a lot of time and headaches.
So, the next time you’re writing Python code, don’t skip the docstrings! They’re more than just a nice-to-have—they’re the key to making your code understandable and professional.
Go ahead and give them a try today!
Remember - IIf you want to go from complete beginner to being able to build any Python project or app your mind can think of, then be sure to check out Andrei's Complete Python Developer course:
It’ll take you from an absolute beginner and teach you everything you need to get hired ASAP and ace the tech interview.
This is the only Python course you need if you want to go from complete Python beginner to getting hired as a Python Developer this year!
Alternatively, if you're already pretty good at Python and want to build some interesting and useful projects, why not check out my course on Python Automation:
It'll show you how to automate all of the boring or repetitive tasks in you life - and makes for some pretty stand out portfolio projects!
Plus, as part of your membership, you'll get access to both of these courses and others, and be able to join me and 1,000s of other people (some who are alumni mentors and others who are taking the same courses that you will be) in the ZTM Discord.
Ask questions, help others, or just network with other Python Developers, students, and tech professionals.