Fix a few stylistic things, and add docs for autosummary_generate.

This commit is contained in:
Georg Brandl 2009-04-13 08:40:56 +00:00
parent ae1c7f9d56
commit 4d249fa3e4
4 changed files with 87 additions and 82 deletions

View File

@ -6,33 +6,34 @@
.. module:: sphinx.ext.autosummary .. module:: sphinx.ext.autosummary
:synopsis: Generate autodoc summaries :synopsis: Generate autodoc summaries
.. versionadded: 0.6 .. versionadded:: 0.6
This extension generates function/method/attribute summary lists, This extension generates function/method/attribute summary lists, similar to
similar to those output eg. by Epydoc and other API doc generation those output e.g. by Epydoc and other API doc generation tools. This is
tools. This is especially useful when your docstrings are long and especially useful when your docstrings are long and detailed, and putting each
detailed, and putting each one of them on a separate page makes one of them on a separate page makes them easier to read.
them easier to read.
The :mod:`sphinx.ext.autosummary` extension does this in two parts: The :mod:`sphinx.ext.autosummary` extension does this in two parts:
1. There is an :dir:`autosummary` directive for generating summary 1. There is an :dir:`autosummary` directive for generating summary listings that
listings that contain links to the documented items, and short contain links to the documented items, and short summary blurbs extracted
summary blurbs extracted from their docstrings. from their docstrings.
2. The convenience script :program:`sphinx-autogen` or the new
:confval:`autosummary_generate` config value can be used to generate short
"stub" files for the entries listed in the :dir:`autosummary` directives.
These by default contain only the corresponding :mod:`sphinx.ext.autodoc`
directive.
2. The convenience script :program:`sphinx-autogen` can be used to
generate short "stub" files for the entries listed in the
:dir:`autosummary` directives. These by default contain only the
corresponding :mod:`sphinx.ext.autodoc` directive.
.. directive:: autosummary .. directive:: autosummary
Insert a table that contains links to documented items, and a short Insert a table that contains links to documented items, and a short summary
summary blurb (the first sentence of the docstring) for each of them. blurb (the first sentence of the docstring) for each of them. The
The :dir:`autosummary` directive can also optionally serve as :dir:`autosummary` directive can also optionally serve as a :dir:`toctree`
a :dir:`toctree` entry for the included items. entry for the included items.
For example,:: For example, ::
.. currentmodule:: sphinx .. currentmodule:: sphinx
@ -53,14 +54,14 @@ The :mod:`sphinx.ext.autosummary` extension does this in two parts:
.. currentmodule:: sphinx.ext.autosummary .. currentmodule:: sphinx.ext.autosummary
Autosummary preprocesses the docstrings and signatures with the same Autosummary preprocesses the docstrings and signatures with the same
:event:`autodoc-process-docstring` and :event:`autodoc-process-docstring` and :event:`autodoc-process-signature`
:event:`autodoc-process-signature` hooks as *autodoc*. hooks as :mod:`~sphinx.ext.autodoc`.
**Options** **Options**
* If you want the :dir:`autosummary` table to also serve as a * If you want the :dir:`autosummary` table to also serve as a :dir:`toctree`
:dir:`toctree` entry, use the ``toctree`` option, for example:: entry, use the ``toctree`` option, for example::
.. autosummary:: .. autosummary::
:toctree: DIRNAME :toctree: DIRNAME
@ -68,14 +69,14 @@ The :mod:`sphinx.ext.autosummary` extension does this in two parts:
sphinx.environment.BuildEnvironment sphinx.environment.BuildEnvironment
sphinx.util.relative_uri sphinx.util.relative_uri
The ``toctree`` option also signals to the :program:`sphinx-autogen` The ``toctree`` option also signals to the :program:`sphinx-autogen` script
script that stub pages should be generated for the entries listed that stub pages should be generated for the entries listed in this
in this directive. The option accepts a directory name as an directive. The option accepts a directory name as an argument;
argument; :program:`sphinx-autogen` will by default place its output :program:`sphinx-autogen` will by default place its output in this
in this directory. directory.
* If you don't want the :dir:`autosummary` to show function signatures * If you don't want the :dir:`autosummary` to show function signatures in the
in the listing, include the ``nosignatures`` option:: listing, include the ``nosignatures`` option::
.. autosummary:: .. autosummary::
:nosignatures: :nosignatures:
@ -83,26 +84,38 @@ The :mod:`sphinx.ext.autosummary` extension does this in two parts:
sphinx.environment.BuildEnvironment sphinx.environment.BuildEnvironment
sphinx.util.relative_uri sphinx.util.relative_uri
:program:`sphinx-autogen` -- generate autodoc stub pages :program:`sphinx-autogen` -- generate autodoc stub pages
-------------------------------------------------------- --------------------------------------------------------
The :program:`sphinx-autogen` script can be used to conveniently The :program:`sphinx-autogen` script can be used to conveniently generate stub
generate stub documentation pages for items included in documentation pages for items included in :dir:`autosummary` listings.
:dir:`autosummary` listings.
For example, the command:: For example, the command ::
$ sphinx-autogen -o generated *.rst $ sphinx-autogen -o generated *.rst
will read all :dir:`autosummary` tables in the :file:`*.rst` files will read all :dir:`autosummary` tables in the :file:`*.rst` files that have the
that have the ``:toctree:`` option set, and output corresponding stub ``:toctree:`` option set, and output corresponding stub pages in directory
pages in directory ``generated`` for all documented items. ``generated`` for all documented items. The generated pages by default contain
The generated pages by default contain text of the form:: text of the form::
sphinx.util.relative_uri sphinx.util.relative_uri
======================== ========================
.. autofunction:: sphinx.util.relative_uri .. autofunction:: sphinx.util.relative_uri
If the ``-o`` option is not given, the script will place the output If the ``-o`` option is not given, the script will place the output files in the
files to the directories specified in the ``:toctree:`` options. directories specified in the ``:toctree:`` options.
Generating stub pages automatically
-----------------------------------
If you do not want to create stub pages with :program:`sphinx-autogen`, you can
also use this new config value:
.. confval:: autosummary_generate
A list of documents for which stub pages should be generated. They will be
placed in the directories specified in the ``:toctree:`` options.

View File

@ -108,6 +108,7 @@ def autosummary_toc_visit_latex(self, node):
def autosummary_noop(self, node): def autosummary_noop(self, node):
pass pass
# -- autodoc integration ------------------------------------------------------- # -- autodoc integration -------------------------------------------------------
def get_documenter(obj): def get_documenter(obj):
@ -132,6 +133,7 @@ def get_documenter(obj):
else: else:
return autodoc.DataDocumenter return autodoc.DataDocumenter
# -- .. autosummary:: ---------------------------------------------------------- # -- .. autosummary:: ----------------------------------------------------------
class Autosummary(Directive): class Autosummary(Directive):
@ -195,8 +197,7 @@ class Autosummary(Directive):
def get_items(self, names): def get_items(self, names):
""" """
Try to import the given names, and return a list of Try to import the given names, and return a list of
``[(name, signature, summary_string, real_name), ...]`` ``[(name, signature, summary_string, real_name), ...]``.
""" """
prefixes = [''] prefixes = ['']
prefixes.insert(0, self.state.document.settings.env.currmodule) prefixes.insert(0, self.state.document.settings.env.currmodule)
@ -253,8 +254,7 @@ class Autosummary(Directive):
""" """
Generate a proper table node for autosummary:: directive. Generate a proper table node for autosummary:: directive.
*items* is a list produced by :meth:`get_items` *items* is a list produced by :meth:`get_items`.
""" """
table = nodes.table('') table = nodes.table('')
group = nodes.tgroup('', cols=2) group = nodes.tgroup('', cols=2)
@ -291,10 +291,7 @@ class Autosummary(Directive):
return table return table
def mangle_signature(sig, max_chars=30): def mangle_signature(sig, max_chars=30):
""" """Reformat a function signature to a more compact form."""
Reformat function signature to a more compact form.
"""
sig = re.sub(r"^\((.*)\)$", r"\1", sig) + ", " sig = re.sub(r"^\((.*)\)$", r"\1", sig) + ", "
r = re.compile(r"(?P<name>[a-zA_Z0-9_*]+)(?P<default>=.*?)?, ") r = re.compile(r"(?P<name>[a-zA_Z0-9_*]+)(?P<default>=.*?)?, ")
items = r.findall(sig) items = r.findall(sig)
@ -327,6 +324,7 @@ def mangle_signature(sig, max_chars=30):
sig = unicode(sig).replace(u" ", u"\u00a0") sig = unicode(sig).replace(u" ", u"\u00a0")
return u"(%s)" % sig return u"(%s)" % sig
# -- Importing items ----------------------------------------------------------- # -- Importing items -----------------------------------------------------------
def import_by_name(name, prefixes=[None]): def import_by_name(name, prefixes=[None]):

View File

@ -29,7 +29,8 @@ from jinja2 import Environment, PackageLoader
from sphinx.ext.autosummary import import_by_name, get_documenter from sphinx.ext.autosummary import import_by_name, get_documenter
from sphinx.util import ensuredir from sphinx.util import ensuredir
def main(argv):
def main(argv=sys.argv):
usage = """%prog [OPTIONS] SOURCEFILE ...""" usage = """%prog [OPTIONS] SOURCEFILE ..."""
p = optparse.OptionParser(usage.strip()) p = optparse.OptionParser(usage.strip())
p.add_option("-o", "--output-dir", action="store", type="string", p.add_option("-o", "--output-dir", action="store", type="string",
@ -53,9 +54,7 @@ def _simple_info(msg):
def _simple_warn(msg): def _simple_warn(msg):
print >>sys.stderr, 'WARNING: ' + msg print >>sys.stderr, 'WARNING: ' + msg
#------------------------------------------------------------------------------ # -- Generating output ---------------------------------------------------------
# Generating output
#------------------------------------------------------------------------------
# create our own templating environment, for module template only # create our own templating environment, for module template only
env = Environment(loader=PackageLoader('sphinx.ext.autosummary', 'templates')) env = Environment(loader=PackageLoader('sphinx.ext.autosummary', 'templates'))
@ -94,13 +93,13 @@ def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
try: try:
if inspect.ismodule(obj): if inspect.ismodule(obj):
# XXX replace this with autodoc's API?
tmpl = env.get_template('module') tmpl = env.get_template('module')
def get_items(mod, typ): def get_items(mod, typ):
return [getattr(mod, name).__name__ return [
for name in dir(mod) getattr(mod, name).__name__ for name in dir(mod)
if get_documenter(getattr(mod,name)).objtype==typ] if get_documenter(getattr(mod, name)).objtype == typ
]
functions = get_items(obj, 'function') functions = get_items(obj, 'function')
classes = get_items(obj, 'class') classes = get_items(obj, 'class')
@ -139,15 +138,12 @@ def format_classmember(name, directive):
return '.. currentmodule:: %s\n\n.. %s:: %s\n' % (mod, directive, name) return '.. currentmodule:: %s\n\n.. %s:: %s\n' % (mod, directive, name)
#------------------------------------------------------------------------------ # -- Finding documented entries in files ---------------------------------------
# Finding documented entries in files
#------------------------------------------------------------------------------
def get_documented_in_files(filenames): def get_documented_in_files(filenames):
""" """
Find out what items are documented in source/*.rst Find out what items are documented in source/*.rst.
See `get_documented_in_lines`. See `get_documented_in_lines`.
""" """
documented = {} documented = {}
for filename in filenames: for filename in filenames:
@ -161,7 +157,6 @@ def get_documented_in_docstring(name, module=None, filename=None):
""" """
Find out what items are documented in the given object's docstring. Find out what items are documented in the given object's docstring.
See `get_documented_in_lines`. See `get_documented_in_lines`.
""" """
try: try:
obj, real_name = import_by_name(name) obj, real_name = import_by_name(name)
@ -175,20 +170,17 @@ def get_documented_in_docstring(name, module=None, filename=None):
def get_documented_in_lines(lines, module=None, filename=None): def get_documented_in_lines(lines, module=None, filename=None):
""" """
Find out what items are documented in the given lines Find out what items are documented in the given lines.
Returns
-------
documented : dict of list of (filename, title, keyword, toctree)
Dictionary whose keys are documented names of objects.
The value is a list of locations where the object was documented.
Each location is a tuple of filename, the current section title,
the name of the directive, and the value of the :toctree: argument
(if present) of the directive.
Returns a dict of lists of (filename, title, keyword, toctree) and whose
keys are documented names of objects. The value is a list of locations
where the object was documented. Each location is a tuple of filename, the
current section title, the name of the directive, and the value of the
:toctree: argument (if present) of the directive.
""" """
title_underline_re = re.compile("^[-=*_^#]{3,}\s*$") title_underline_re = re.compile("^[-=*_^#]{3,}\s*$")
autodoc_re = re.compile(".. auto(function|method|attribute|class|exception|module)::\s*([A-Za-z0-9_.]+)\s*$") autodoc_re = re.compile(r'.. auto(function|method|attribute|class|'
r'exception|module)::\s*([A-Za-z0-9_.]+)\s*$')
autosummary_re = re.compile(r'^\.\.\s+autosummary::\s*') autosummary_re = re.compile(r'^\.\.\s+autosummary::\s*')
module_re = re.compile(r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') module_re = re.compile(r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$')
autosummary_item_re = re.compile(r'^\s+([_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') autosummary_item_re = re.compile(r'^\s+([_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?')
@ -216,12 +208,13 @@ def get_documented_in_lines(lines, module=None, filename=None):
m = autosummary_item_re.match(line) m = autosummary_item_re.match(line)
if m: if m:
name = m.group(1).strip() name = m.group(1).strip()
if current_module and not name.startswith(current_module + '.'): if current_module and \
not name.startswith(current_module + '.'):
name = "%s.%s" % (current_module, name) name = "%s.%s" % (current_module, name)
documented.setdefault(name, []).append( documented.setdefault(name, []).append(
(filename, current_title, 'autosummary', toctree)) (filename, current_title, 'autosummary', toctree))
continue continue
if line.strip() == '': if not line.strip():
continue continue
in_autosummary = False in_autosummary = False
@ -257,7 +250,6 @@ def get_documented_in_lines(lines, module=None, filename=None):
return documented return documented
#------------------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -8,6 +8,7 @@
:copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS. :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details. :license: BSD, see LICENSE for details.
""" """
import string import string
from util import * from util import *
@ -20,7 +21,8 @@ def test_mangle_signature():
() :: () () :: ()
(a, b, c, d, e) :: (a, b, c, d, e) (a, b, c, d, e) :: (a, b, c, d, e)
(a, b, c=1, d=2, e=3) :: (a, b[, c, d, e]) (a, b, c=1, d=2, e=3) :: (a, b[, c, d, e])
(a, b, aaa=1, bbb=1, ccc=1, eee=1, fff=1, ggg=1, hhh=1, iii=1, jjj=1) :: (a, b[, aaa, bbb, ccc, eee, fff, ...]) (a, b, aaa=1, bbb=1, ccc=1, eee=1, fff=1, ggg=1, hhh=1, iii=1, jjj=1)\
:: (a, b[, aaa, bbb, ccc, eee, fff, ...])
(a, b, c=(), d=<foo>) :: (a, b[, c, d]) (a, b, c=(), d=<foo>) :: (a, b[, c, d])
(a, b, c='foobar()', d=123) :: (a, b[, c, d]) (a, b, c='foobar()', d=123) :: (a, b[, c, d])
""" """