There are a few ways to do it. I think the most sensible in your case would be .. code-block::

""" This is a module documentation

Use this module like this:

.. code-block:: python

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

Notice the blank line between the directive and the code block - it must be there in order for the block to render properly.

Answer from Błażej Michalik on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › example code within docstrings
r/learnpython on Reddit: Example Code Within Docstrings
August 21, 2020 -

I am currently creating documentation using Sphinx for a library I have created. However, I am struggling to find out the best way to include examples on how to use the functions within the docstring.

Basically I want include a code snippet, that will get picked up by Sphinx and then by rst2pdf, and formatted into a code block. However, when I search for python docstrings and code examples, I just get info on how to create them.

Is what I am doing possible? If so, what is the best way to deal with this.

🌐
GitHub
github.com › modelcontextprotocol › python-sdk › actions › runs › 22197782296
docs: add code fences to `Example:` docstring blocks · modelcontextprotocol/python-sdk@72d1f38
The official Python SDK for Model Context Protocol servers and clients - docs: add code fences to `Example:` docstring blocks · modelcontextprotocol/python-sdk@72d1f38
Author: modelcontextprotocol
Discussions

python - How do I insert highlight or code-block into Sphinx-style docstrings? - Stack Overflow
For example: def foo(): ''' .. highlight:: python import sys ''' Doesn't produce desired output (it prints the word "highlight" verbatim and doesn't format the following code in any More on stackoverflow.com
🌐 stackoverflow.com
Docstring vs Comments
Docstrings are easily obtainable by other Python tools dynamically just by inspecting your objects. This is useful for tools that do things like generating API documentation. Comments are, by comparison, more difficult for such tools to use in part because comments are discarded by the compiler whereas docstrings are a part of your object (see .__doc__ attribute of any function, class, etc.). They're not necessarily interchangable tools, however. They're different tools for different purposes. Also, docstrings only work in certain places like at the very beginning of modules, classes, or functions. Comments, on the other hand, can be placed anywhere. More on reddit.com
🌐 r/learnpython
4
8
September 11, 2024
Example Code Within Docstrings
Code blocks are created by using the code-block directive: .. code-block:: python. The default language is Python, so you can also shorten it to ::: """ This is a docstring :: import this # this is a code block """ https://www.sphinx-doc.org/en/1.2/markup/code.html More on reddit.com
🌐 r/learnpython
6
1
August 21, 2020
What are your preferred conventions for documenting python code?
Module docstrings. I don't think I've ever worked with someone else who writes them. Open up a file for the first time, see 30 lines of imports and a bunch of functions that call each other, the file name is generic and provides no context. This tier of missing documentation is really painful. Just explain what should be used outside the module, specific terminology used here and how things link together. I'm tired of building up the design in my mind from all the implementation bits. More on reddit.com
🌐 r/Python
20
22
December 8, 2022
🌐
Readthedocs
sphinxcontrib-napoleon.readthedocs.io › en › latest › example_google.html
Example Google Style Python Docstrings — napoleon 0.7 documentation
Sections support any reStructuredText ... literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. Attributes: module_level_variable1 (int): Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an ...
🌐
Medium
medium.com › jit-team › documenting-python-code-with-docstrings-b999ee164ff2
Documenting Python code with docstrings | by Adam Czapski | Jit Team | Medium
September 14, 2022 - For example, epydoc can be used to generate documentation from a single source file, without the need to create a separate documentation project. Pygment can also generate documentation from a single source file. One of the most important things to document in Python code are docstrings. Docstrings are strings that are used to document a code block, and they are typically placed at the beginning of a code block.
🌐
iO Flood
ioflood.com › blog › python-docstring
Python Docstring Usage Guide (With Examples)
December 11, 2023 - They enhance code understandability and maintainability. For a more advanced understanding and tips on writing effective Docstrings, read on! def hello_world(): """This function prints 'Hello, World!'""" print('Hello, World!') ... A Python Docstring is a string literal that you write as the first statement in a module, function, class, or method definition.
🌐
Sphinx-gallery
sphinx-gallery.github.io › dev › tutorials › plot_parse.html
Alternating text and code — Sphinx-Gallery 0.20.dev0-git documentation
This example demonstrates how to alternate text and code blocks and some edge cases. It was designed to be compared with the :download:`source Python script <plot_parse.py>`.""" # %% # This is the first text block and directly follows the header docstring above.
Find elsewhere
🌐
YouTube
youtube.com › watch
python class docstring convention - YouTube
Instantly Download or Run the code at https://codegive.com title: python class docstring convention tutorialintroduction:documentation is a crucial aspect o...
Published: February 24, 2024
🌐
AskPython
askpython.com › python › python-docstring
Python Docstring - AskPython
February 16, 2023 - Let’s say we have defined the above function and class in docstrings.py file. Every Python script is also a module. We can define this module docstring as: """ This module shows some examples of Python Docstrings Classes: Employee Functions: multiply(a, b) """
🌐
Programiz
programiz.com › python-programming › docstrings
Python Docstrings (With Examples)
As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code.
🌐
Umn
docs.cems.umn.edu › intro › Prt_01_Lssn_06_Code_Blocks_Functions.html
7. Python Code Blocks: Functions — Intro to Scientific Python
There are numerous ways to format a docstring, and sometimes when browsing Python source code, you may see docstrings in this format: def convert_temp_docs(temp, output_unit='K'): """ Convert temperature from one unit to another. Returns temperature and output_unit. :param temp: Temperature that will be converted :type: float :param output_unit: String designating the output unit. Can be one of 'F', 'C', 'R', 'K'. Default is 'K' :type: str """ pass · This is an example of the ReStructuredText format for styling docstrings.
🌐
JetBrains
jetbrains.com › guide › python › tutorials › sphinx_sites › documentation
Documenting Code - Python
February 17, 2023 - # About `MyDemo` Let's take a look at this Python class. ```{eval-rst} .. autoclass:: my_demo.MyDemo :members: ``` In this example, documentation for the MyDemo class will be inserted into the api page. Here's what the rendered output looks like: It's very rich output, with lots of links generated to imports, symbols, etc. We can actually do better, with richer formatting in docstrings and type hints.
🌐
Pandas
pandas.pydata.org › docs › _sources › development › contributing_docstring.rst.txt
.. _docstring: {{ header }} ====================== pandas docstring guide
Examples -------- >>> add(2, 2) 4 >>> add(25, 0) 25 >>> add(10, -10) 0 """ return num1 + num2 · Some standards regarding docstrings exist, which make them easier to read, and allow them be easily exported to other formats such as html or pdf. The first conventions every Python docstring should follow are defined in PEP-257 <https://www.python.org/dev/peps/pep-0257/>_.
🌐
PyTorch
docs.pytorch.org › FBGEMM › general › documentation › Python.html
Adding Documentation to Python Code — FBGEMM 1.5.0 documentation
Follow these instructions to document, ... a new Python docstring: Add the docstring directly under the name of the target method. At a very minimum, please add descriptions of: ... Other sections such as Todo, Note, and Example should be added as needed. ... def example_method(alignment: c_size_t, param: float) -> int: """ This class is an example of how you can write docstrings. You can add multiple lines of those descriptions. Make sure to include useful information about your method. **Code Example:** ...
🌐
Real Python
realpython.com › documenting-python-code
Documenting Python Code: A Complete Guide – Real Python
July 17, 2026 - All four blocks above document the same function—the same summary, the same file_loc and print_cols parameters, and the same list return—just in different syntaxes. Flip between them in the widget below to watch where each shared field lands in every format: Interactive diagram — enable JavaScript to view. Note: To learn more about docstrings and how to create them, check out How to Write Docstrings in Python.
🌐
JetBrains
jetbrains.com › pycharm › guide › tutorials › sphinx_sites › documentation
Documenting Code - JetBrains Guide
February 17, 2023 - # About `MyDemo` Let's take a look at this Python class. ```{eval-rst} .. autoclass:: my_demo.MyDemo :members: ``` In this example, documentation for the MyDemo class will be inserted into the api page. Here's what the rendered output looks like: It's very rich output, with lots of links generated to imports, symbols, etc. We can actually do better, with richer formatting in docstrings and type hints.
🌐
Sphinx
sphinx-doc.org › en › master › usage › extensions › example_google.html
Example Google Style Python Docstrings — Sphinx documentation
Sections support any reStructuredText ... literal blocks:: $ python example_google.py Section breaks are created by resuming unindented text. Section breaks are also implicitly created anytime a new section starts. Attributes: module_level_variable1 (int): Module level variables may be documented in either the ``Attributes`` section of the module docstring, or in an ...
🌐
Hive
hive.blog › hive-122108 › @alrashel › python-rules-of-coding-docstrings
Python Rules Of Coding: Docstrings — Hive
May 7, 2020 - Python docstring (documentation string) is a string literal and it can be used in any code block, i.e., the class, module, function, method definition. It provides us a handy way of attaching the relevant documentation within the code block.
🌐
Lftechnology
coding-guidelines.lftechnology.com › docstrings
Convention for docstrings | Leapfrog Coding Guidelines
While comments are also written alongside code, docstrings are different from comments. While comments start with a '#' symbol, docstrings are also enclosed withing triple double quotes """This is a docstring""". The placement of docstrings is also crucial. Docstrings placed arbitrarily may simply be construed as a comment · To illustrate this try the following in the python console · class Test: """This is a class docstring""" def example_method(): """This is a method docstring """ pass def example_method_2(): # This is a comment pass