How do I document a module in Python? - 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.

Related

Can I use Sphinx automodule but drop the module name in the signature?

I have a module mod with some submodule submod and use .. automodule:: mod.submod to generate documentation for it.
The signatures of the elements (functions, classes etc.) in the modules now show the qualified name, like mod.submod.my_function(*args, **kwargs).
I would instead like Sphinx to just show the name of the function, i.e. the signature my_function(*args, **kwargs).
Do I have any way to drop the leading module and submodules in the signature?
Omitting module and package names preceding functions, methods and variables is done by setting the add_module_name configuration in your conf.py:
add_module_names = False
This is not obvious because of the numerous autodoc configurations that together with the sphinx-napoleon configurations make you expect the configuration elsewhere.
Yes, try this in docs/mod/submod.rst:
.. automodule:: mod.submod
.. autofunction:: my_function
See example HTML build and reST source in Pyramid documentation.
Bonus: see the Sphinx docs for Cross-referencing syntax:
If you prefix the content with ~, the link text will only be the last component of the target. For example, :py:meth:~Queue.Queue.get will refer to Queue.Queue.get but only display get as the link text.

How to exclude imports from automodapi output?

I am trying to use automodapi to generate documentation for my Django project. When I call automodapi like this:
.. automodapi:: mypackage.mymodule
the output includes all imported classes and functions, e.g, the Django Model class, in the index of Functions and Classes. I would like to exclude the imports and only list those classes and functions declared in the module I specified.
I couldn't see anything about this in the documentation.
Is there a way to do this, preferably without modifying modules?
UPDATE: #saimn has provided a working solution using __all__ but my project doesn't use __all__. It would be nice if there was a solution that didn't involve modifying the modules.
Patching automodapi to only include locals also addresses this issue while not requiring any changes to your code:
def patch_automodapi(app):
"""Monkey-patch the automodapi extension to exclude imported members"""
from sphinx_automodapi import automodsumm
from sphinx_automodapi.utils import find_mod_objs
automodsumm.find_mod_objs = lambda *args: find_mod_objs(args[0], onlylocals=True)
def setup(app):
app.connect("builder-inited", patch_automodapi)
Source: https://github.com/astropy/sphinx-automodapi/issues/119
The above snippet goes into your conf.py sphinx configuration file.
You can use the __all__ variable (this should probably be stated more clearly in the documentation).

Refer reST label in python docstring

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.

How do I create documentation with Pydoc?

I'm trying to create a document out of my module. I used pydoc from the command-line in Windows 7 using Python 3.2.3:
python "<path_to_pydoc_>\pydoc.py" -w myModule
This led to my shell being filled with text, one line for each file in my module, saying:
no Python documentation found for '<file_name>'
It's as if Pydoc's trying to get documentation for my files, but I want to autocreate it. I couldn't find a good tutorial using Google. Does anyone have any tips on how to use Pydoc?
If I try to create documentation from one file using
python ... -w myModule\myFile.py
it says wrote myFile.html, and when I open it, it has one line of text saying:
# ../myModule/myFile.py
Also, it has a link to the file itself on my computer, which I can click and it shows what's inside the file on my web browser.
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'
yourcode_dir$ pydoc -w original
wrote original.html
pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:
"""
This example module shows various types of documentation available for use
with pydoc. To generate HTML documentation for this module issue the
command:
pydoc -w foo
"""
class Foo(object):
"""
Foo encapsulates a name and an age.
"""
def __init__(self, name, age):
"""
Construct a new 'Foo' object.
:param name: The name of foo
:param age: The ageof foo
:return: returns nothing
"""
self.name = name
self.age = age
def bar(baz):
"""
Prints baz to the display.
"""
print baz
if __name__ == '__main__':
f = Foo('John Doe', 42)
bar("hello world")
The first docstring provides instructions for creating the documentation with pydoc. There are examples of different types of docstrings so you can see how they look when generated with pydoc.
As RocketDonkey suggested, your module itself needs to have some docstrings.
For example, in myModule/__init__.py:
"""
The mod module
"""
You'd also want to generate documentation for each file in myModule/*.py using
pydoc myModule.thefilename
to make sure the generated files match the ones that are referenced from the main module documentation file.
works on windows7:
python -m pydoc -w my_module

Convert Python 3 to "simple" python that can be read by autodoc

I have a written a program in Python 3 and are using Sphinx to document it. Sphinx's autodoc is great, however it only works with Python 2. Some modules work fine in autodoc, however modules don't. Some examples: Python 2 complains about Python 3 style metaclasses, and some modules which don't exist anymore in Python 2 such as configparser. This is annoying as it cannot import the docstrings from that file.
I don't want to rewrite the whole program in Python 2, however I want to use autodoc.
One idea I had was a small program that read each Python file and removed all functionality but just left the basic function and classes with their docstrings (because autodoc imports each module and reads the docstring of a specific function or class).
import configparser
import os
class TestClass:
"""
I am a class docstring.
"""
def method(self, argument):
"""
I am a method docstring.
"""
#Some code here
print(os.getcwd())
def TestFunction():
"""
I am a function docstring.
"""
#Some more useless code here
return os.path.join("foo", "bar")
into...
class TestClass:
"""
I am a class docstring.
"""
def method(self, argument):
"""
I am a method docstring.
"""
pass
def TestFunction():
"""
I am a function docstring.
"""
pass
In this way the processed code can be read by autodoc, but still have the docstrings which is what I really need. Is this the best way of going about this, and does anyone have any suggestions as to how to write the little program which converts the code.
I can remove the metaclass problem very easily with some regular expressions, but I am struggling with the rest.
m = re.search("\(metaclass=.*\)", file_content)
if m:
file_content = "".join(file_content[:m.start()], file_content[m.end():])
Would the ast module be useful?
Thanks.
You can just install the development version of sphinx, which supports python 3.
pip-3.2 install hg+https://bitbucket.org/birkenfeld/sphinx
I tested the autodoc feature on your class and it worked.
What tends to be the solution is sprinkling try/except clauses in your code.
Python 2.6 has configparser but it is known as ConfigParser (python 3 changed the camelcase names to all lower case)
so something like:
try:
import configparser
except ImportError:
#we are in 2.x
import ConfigParser as configparser
you might want to do a few things like this where it's broken. between the two. metaclasses though between the two I'm not sure to handle.
There's a 3to2 library that can convert Python 3 code to python 2. You could try this in conjunction with Sphinx.

Categories

Resources