Table of Contents
What Will You Learn
In this tutorial, you'll explore how to use docstrings in Python to create clean, readable documentation directly within your functions. You'll learn the correct syntax for single-line and multi-line docstrings, follow formatting standards like PEP 257, and understand how tools like help()
and IDEs use docstrings to assist development. Perfect for writing professional, self-explanatory code.
As a beginner learning Python, one of the most overlooked but essential practices is writing proper documentation using docstrings. Docstrings help describe what a function,
class, or module does — directly within your code. Unlike regular comments, they are stored as part of the object and can be accessed programmatically using built-in functions
like help()
or .__doc__
. This makes them an important part of writing clear, maintainable, and collaborative code.
If you plan to share your code with others, build reusable libraries, or simply want to make future debugging easier for yourself — docstrings are the foundation of good documentation. By using them early in your learning journey, you build the habit of writing self-explanatory code. Clear docstrings help you think through your function’s purpose, inputs, outputs, and edge cases. This leads to better design decisions and fewer bugs. Writing docstrings is not optional — it’s a best practice for professional code.
What Are Docstrings in Python?
Docstrings in Python are string literals used to document modules, functions, classes, or methods. They are placed as the first statement in the definition and enclosed in triple
quotes: """docstring here"""
. Unlike regular comments, docstrings become part of the object’s metadata and can be retrieved using help()
or accessed via
the .__doc__
attribute.
This makes them useful not just for humans reading the code, but also for tools like IDEs, linters, and documentation generators.
Python supports both single-line and multi-line docstrings. A single-line docstring is sufficient for simple functions, while multi-line docstrings are used to describe more complex behavior, parameters, and return values. Following standard formats like PEP 257 or reStructuredText can help keep your documentation consistent and tool-friendly. Good docstrings clearly explain what the function does, what arguments it takes, and what it returns — without repeating the function name or restating obvious things. They are especially helpful when revisiting code after weeks or when collaborating with others. In short, docstrings serve as an internal guide for anyone who reads or uses your code.
What Are the Best Practices for Writing Docstrings in Python?
When writing docstrings in Python, follow clear and consistent formatting. Always place the docstring immediately after the function, class, or module definition using triple quotes. Begin with a summary line that briefly describes what the object does. Use full sentences, write in the present tense, and avoid repeating the function or class name.
For functions with parameters, include a section describing each argument and the return value. Stick to common conventions like PEP 257 or Google-style docstrings for uniformity. Keep it readable — your goal is to make the purpose of the code obvious.
def add(a, b):
"""Add two numbers and return the result.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of a and b.
"""
return a + b
In the example above, the summary line describes the purpose. Parameters and return types are listed with clear types and explanations. This makes the function easier to understand and use without reading its internal logic.
What Are the Benefits of Using Docstrings in Python?
Docstrings bring clarity, structure, and professionalism to your code. They explain the intent behind your functions, classes, or modules without needing to inspect the logic. When used correctly, they improve collaboration and help tools generate useful documentation automatically. Even in solo projects, well-written docstrings help you understand your own code after time has passed. They also make codebases easier to navigate and maintain. Whether you're building APIs, libraries, or scripts — docstrings are essential.
- Improved code readability: Developers can understand your code faster by reading docstrings instead of diving into implementation details.
- Better collaboration: Teams benefit from clear documentation, reducing misunderstandings and onboarding time.
- IDE integration: Many editors show docstrings as inline tooltips or autocomplete suggestions, speeding up development.
- Accessible help(): Users can run
help(function)
to immediately see what the function does. - Supports documentation tools: Tools like Sphinx or pdoc use docstrings to generate external documentation automatically.
- Encourages clean design: Writing the docstring forces you to think clearly about a function’s input, output, and responsibility.
- Makes testing easier: Descriptions in docstrings help testers understand expected behavior more quickly.
Common Beginner Mistakes
Missing Docstrings Entirely
Many beginners skip docstrings altogether, assuming the code speaks for itself. This leads to poor maintainability and confusion when revisiting code later. Without documentation, others — or even your future self — won't understand what your function does, what inputs it expects, or what it returns. Always add a docstring to every function, class, or module you write, even if it’s short.
# Incorrect
def greet(name):
return f"Hello, {name}"
# Correct
def greet(name):
"""Return a personalized greeting."""
return f"Hello, {name}"
Using Comments Instead of Docstrings
Beginners often use regular comments (#
) instead of docstrings. While comments are helpful, they aren’t accessible through help()
or documentation
tools. A proper docstring is part of the object and is stored in its __doc__
attribute, making it easier to retrieve and integrate with development environments. Use
triple quotes for real documentation.
# Incorrect
def square(x):
# This function returns the square of a number
return x * x
# Correct
def square(x):
"""Return the square of a number."""
return x * x
Repeating the Function Name in the Docstring
It’s a common mistake to start a docstring by repeating the function name or phrasing it awkwardly. For example, “This function calculates…” is unnecessary. A better practice is to begin directly with a verb describing the action. This keeps documentation cleaner and more consistent across codebases.
# Incorrect
def calculate_area(radius):
"""This function calculates the area of a circle."""
return 3.14 * radius * radius
# Correct
def calculate_area(radius):
"""Calculate the area of a circle."""
return 3.14 * radius * radius
Not Describing Parameters and Return Values
Omitting descriptions of parameters and return values makes the docstring less useful, especially for complex functions. Beginners often write just a summary line. While helpful, it’s not enough. Documenting parameters and return types helps other developers understand how to use your function correctly.
# Incomplete
def divide(a, b):
"""Divide two numbers."""
return a / b
# Complete
def divide(a, b):
"""Divide two numbers.
Parameters:
a (float): Numerator.
b (float): Denominator.
Returns:
float: The result of division.
"""
return a / b
Writing Docstrings in Inconsistent Style
Switching styles between functions (e.g., Google style, NumPy style, or no structure at all) confuses readers and breaks documentation tools. Choose a standard format and use it consistently throughout your codebase. This improves readability and ensures compatibility with automated tools.
# Inconsistent and unclear
def power(x, y):
"""Raises x to the power of y. Inputs: x, y. Returns result."""
return x ** y
# Better and consistent (Google style)
def power(x, y):
"""Raise x to the power of y.
Args:
x (int): The base number.
y (int): The exponent.
Returns:
int: The result of x raised to the power of y.
"""
return x ** y
Placing the Docstring in the Wrong Position
Another frequent mistake is placing the docstring after code inside the function. Docstrings must be the first statement in the function or class to be recognized by Python as
the official documentation. Anything placed after will be ignored by tools like help()
. Always begin your function body with the docstring.
# Incorrect
def greet(name):
result = f"Hi, {name}"
"""Return a greeting message.""" # This is ignored
return result
# Correct
def greet(name):
"""Return a greeting message."""
result = f"Hi, {name}"
return result
Frequently Asked Questions (FAQ)
How to use docstrings in Python?
In Python, a docstring is used to document a function, class, or module. You place a string literal (enclosed in triple quotes) immediately after the definition line. This
string becomes part of the object's metadata and can be accessed using the help()
function or the __doc__
attribute. A typical docstring includes a
short summary of the object’s purpose, followed by descriptions of its parameters and return values if applicable.
Example:
def greet(name):
"""Return a greeting with the given name."""
return f"Hello, {name}"
This makes your code more understandable and allows tools to generate helpful documentation automatically.
How to write docstrings for class in Python?
To write a docstring for a class in Python, place a triple-quoted string directly under the class definition line. This docstring should describe the purpose of the class and
can include a brief summary of its attributes and usage. If the class has a constructor method __init__
, it should also include a separate docstring for
documenting constructor arguments.
Example:
class User:
"""Represents a system user with login credentials."""
def __init__(self, username, email):
"""Initialize user with username and email."""
self.username = username
self.email = email
Well-documented classes help other developers understand the object model without reading through all its methods.
How to view docstrings in Python?
You can view docstrings in Python using the built-in help()
function or by accessing the __doc__
attribute of an object. These methods work with
functions, classes, and modules. This is especially useful when working in an interactive environment like the Python shell, IPython, or Jupyter Notebook.
Example:
def greet(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet.__doc__)
# or
help(greet)
This makes it easy to access documentation without digging into the source code, especially when using external libraries.
How does markdown enhance Python docstrings?
Python does not natively support Markdown in docstrings, but many tools that parse and render docstrings — such as Sphinx with extensions or Jupyter Notebooks — interpret Markdown for better formatting. By writing your docstrings using Markdown syntax, you improve their readability in rendered documentation or interactive environments.
For example, you can use lists, bold, italics, and code formatting:
def get_info():
"""
**Returns:**
- `name` *(str)*: The user's name
- `email` *(str)*: The user's email
"""
pass
This approach is helpful when creating modern, readable documentation for APIs or libraries.
What is the difference between comments and docstrings?
Comments in Python are written with the #
symbol and are ignored by the interpreter. They are used for internal notes or clarifying specific lines of code.
Docstrings, on the other hand, are string literals enclosed in triple quotes and placed at the start of functions, classes, or modules. They are stored in the object’s
__doc__
attribute and used for documentation.
Docstrings can be accessed with tools like help()
or documentation generators, while comments cannot. Use comments for inline clarification and docstrings for
structural documentation.
Should every function in Python have a docstring?
Yes, ideally every function should have a docstring — especially if it's part of a public API, library, or collaborative project. Even for small internal functions, a one-line summary adds value. Writing docstrings forces you to define the purpose, inputs, and outputs clearly. This improves both design and maintainability.
If a function is trivial and self-explanatory (e.g., return x + 1
), some developers choose to skip it. But as a best practice, always include at least a brief
description, especially in reusable code.