Refer reST label in python docstring - python

I want to refer to reST label in my python method docstring and am expecting Sphinx to generate appropriate links.
I tried the following which does not work for me.
myown.rst
.. my-label:
Some explanation ...
mymodule.py
def somefunc():
""" See :ref:`my-label`. """
... rest of the code ...
This produces "See my-label" as text in the generated html file while I am expecting it to create appropriate hyper-link.
I see this kind of references in python-docs (e.g. see https://docs.python.org/3/library/functions.html#classmethod ) and reference to Function definitions (which is generic explanation). However, this is not generated from docstrings (as can be seen from funcobject.c) .. so I am inclined to think that it is handcrafted rst !!

Based on comment from #mzjn - the section header was missing in the rst file. Adding that and regenerating fixes the issue.

Related

Sphinx documenting dictionary content (a module constant)

This is somewhat related to How to document a module constant in Python? but not same.
I have a constant in the module (its a dict):
possiblestringencodings = dict(
StringsAsBytes=1,
ascii=1,
utf8=1, utf_8=1, U8=1,
utf16=2, utf_16=2, U16=2, utf_16_be=2, utf_16_le=2,
utf32=4, utf_32=4, U32=4, utf_32_be=4, utf_32_le=4,
)
The readthedocs page has (see autodata docs):
.. autodata:: construct.possiblestringencodings
However, this produces the docstring from dict docstring (its ctor). How can I document the content of that dictionary, ONLY its items using Sphinx?
If someone would like to test patching it up, just fork the repo and run "make html" inside docs/ folder.
https://github.com/construct/construct/blob/1b53d9122a2c652db64c6558d101caee5bbbab3a/construct/core.py#L1280
https://github.com/construct/construct/blob/1b53d9122a2c652db64c6558d101caee5bbbab3a/docs/api/strings.rst
The dictionary data member does not have a docstring so you get the one from the dict class.
Add an empty "documentation comment" immediately before the definition (or a docstring immediately after), and you will only get the dictionary items in the output.
#:
possiblestringencodings = dict(
StringsAsBytes=1,
ascii=1,
utf8=1, utf_8=1, U8=1,
utf16=2, utf_16=2, U16=2, utf_16_be=2, utf_16_le=2,
utf32=4, utf_32=4, U32=4, utf_32_be=4, utf_32_le=4,
)
You also need to fully qualify the "core" module:
.. autodata:: construct.core.possiblestringencodings

Sphinx: list of functions in a module

I have some python modules containing mostly functions and a few classes. Each one is documented using sphinx-autodoc in a separate rst. What I want to do is to create a table or list of the module's contents at the top of each page, so for example, of mymodule.py is
def first():
'First function'
def second():
'Second function'
And mymodule.rst is
Page Contents
-------------
:create_page_contents_list:
Members
-------
.. automodule:: mymodule
:members:
Then the output should look something like this:
Page Contents
-------------
first
second
Members
-------
first()
First function
second()
Second function
The question how to do :create_page_contents_list:. I've have a look at using a TOC, but it seems that I would need to manually create an entry for each item. I've also looked at autosummary, but I still need to list the members. Any suggestions for automating this? I'd rather avoid third-party extensions.
You probably want something like the autosummary extension. The actual autosummary extension will not quite do what you want, though.
An example of how you might extend autosummary to auto-detect the contents of the module is given in this answer

Get "flat" member output for sphinx automodule

I'm using the Sphinx autodoc extension to document a module, and I'd like to get a flat list of the module's members in the documentation output.
I tried using the following:
.. automodule:: modname
:members:
However, there are two problems with this:
It includes the module's docstring, which I don't want here.
The name of each entry is prefixed with "modname.", which is completely redundant (since this page is specifically for documenting this module)
However, I haven't been able to find any config options that would let me selectively disable these two aspects while still getting the automatic listing of all of the module members.
My current plan is to just use autofunction (etc) and explicitly enumerate the members to be documented, but I'd still like to know if I missed an easy way to achieve what I originally wanted.
Update: I at least found a workaround for the second part: set add_module_names=False in conf.py. That's a global setting though, so it doesn't really answer my original question.
Looking at this answer to a similar question, I've found that you can use the autodoc-process-docstring event to remove the docstrings from modules appending the following code to your conf.py:
def skip_modules_docstring(app, what, name, obj, options, lines):
if what == 'module':
del lines[:]
def setup(app):
app.connect('autodoc-process-docstring', skip_modules_docstring)
Note that the del statement is needed because, according to the documentation, the modification to lines must happend in place (it you create a new object, it doesn't work).
Finally, you can also use name to filter the docstrings of just a few modules while keeping the ones from others.

Using sphinx to auto-document a python class, module

I have installed Sphinx in order to document some Python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a Python code.
Basically, I have the following Python module:
SegLib.py
And A class called Seg in it. I would like to display the docstrings of the class and module within the generated Sphinx document, and add further formatted text to it.
My index.rst looks like this:
Contents:
.. toctree::
:maxdepth: 2
chapter1.rst
and chapter1.rst:
This is a header
================
Some text, *italic text*, **bold text**
* bulleted list. There needs to be a space right after the "*"
* item 2
.. note::
This is a note.
See :class:`Seg`
But Seg is just printed in bold, and not linked to an auto-generated documentation of the class.
Trying the following didn't help, either:
See :class:`Seg`
Module :mod:'SegLib'
Module :mod:'SegLib.py'
Edit: changed SegLib to segments (thanks, iElectric!), and changed chapter1.rst to:
The :mod:`segments` Module
--------------------------
.. automodule:: segments.segments
.. autoclass:: segments.segments.Seg
Still, can't get Sphinx to directly document functions within a class, or better - to automatically add all the functions within a class to the document. Tried:
.. autofunction:: segments.segments.Seg.sid
and got:
autodoc can't import/find function 'segments.segments.Seg.sid', it reported error: "No module named Seg"
Any ideas how to auto-document the functions and classes with a short command?
Add to the beginning of the file:
.. module:: SegLib
Try using :autoclass: directive for class doc.
BTW: module names should be lower_case.
EDIT: I learned a lot from reading other source files.

How do I document a module in Python?

That's it. If you want to document a function or a class, you put a string just after the definition. For instance:
def foo():
"""This function does nothing."""
pass
But what about a module? How can I document what a file.py does?
Add your docstring as the first statement in the module.
"""
Your module's verbose yet thorough docstring.
"""
import foo
# ...
For packages, you can add your docstring to __init__.py.
For the packages, you can document it in __init__.py.
For the modules, you can add a docstring simply in the module file.
All the information is here: http://www.python.org/dev/peps/pep-0257/
Here is an Example Google Style Python Docstrings on how module can be documented. Basically there is an information about a module, how to execute it and information about module level variables and list of ToDo items.
"""Example Google style docstrings.
This module demonstrates documentation as specified by the `Google
Python Style Guide`_. Docstrings may extend over multiple lines.
Sections are created with a section header and a colon followed by a
block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
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
inline docstring immediately following the variable.
Either form is acceptable, but the two should not be mixed. Choose
one convention to document module level variables and be consistent
with it.
Todo:
* For module TODOs
* You have to also use ``sphinx.ext.todo`` extension
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
module_level_variable1 = 12345
def my_function():
pass
...
...
You do it the exact same way. Put a string in as the first statement in the module.
It's easy, you just add a docstring at the top of the module.
For PyPI Packages:
If you add doc strings like this in your __init__.py file as seen below
"""
Please refer to the documentation provided in the README.md,
which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/
"""
# <IMPORT_DEPENDENCIES>
def setup():
"""Verify your Python and R dependencies."""
Then you will receive this in everyday usage of the help function.
help(<YOUR_PACKAGE>)
DESCRIPTION
Please refer to the documentation provided in the README.md,
which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/
FUNCTIONS
setup()
Verify your Python and R dependencies.
Note, that my help DESCRIPTION is triggered by having that first docstring at the very top of the file.

Categories

Resources