Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Xref param type #197

Merged
merged 3 commits into from
Apr 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
*.swo
build
dist
doc/_build
12 changes: 5 additions & 7 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
# After changing this file, check it on:
# http://lint.travis-ci.org/
language: python
dist: xenial
sudo: false
env:
- SPHINX_SPEC="Sphinx==1.2.3"
- SPHINX_SPEC="Sphinx"
matrix:
include:
- python: 3.6
- python: 3.7
env: SPHINX_SPEC="==1.2.3" SPHINXOPTS=""
- python: 3.7
- python: 2.7
env:
- SPHINXOPTS='-W'
cache:
directories:
- $HOME/.cache/pip
before_install:
- sudo apt-get install texlive texlive-latex-extra latexmk
- pip install --upgrade pip setuptools # Upgrade pip and setuptools to get ones with `wheel` support
- pip install pytest numpy matplotlib ${SPHINX_SPEC}
- pip install pytest numpy matplotlib sphinx${SPHINX_SPEC}
script:
- |
python setup.py sdist
Expand Down
2 changes: 1 addition & 1 deletion doc/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#

# You can set these variables from the command line.
SPHINXOPTS =
SPHINXOPTS = -nWT --keep-going
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
Expand Down
5 changes: 4 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@
release = numpydoc.__version__
version = re.sub(r'(\d+\.\d+)\.\d+(.*)', r'\1\2', numpydoc.__version__)
version = re.sub(r'(\.dev\d+).*?$', r'\1', version)
numpydoc_xref_param_type = True
numpydoc_xref_ignore = {'optional', 'type_without_description', 'BadException'}

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down Expand Up @@ -269,5 +271,6 @@
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
'scikitlearn': ('http://scikit-learn.org/stable/', None),
'numpy': ('https://www.numpy.org/devdocs', None),
'sklearn': ('http://scikit-learn.org/stable/', None),
}
8 changes: 4 additions & 4 deletions doc/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ def foo(var1, var2, long_var_name='hi'):

See Also
--------
otherfunc : relationship (optional)
newfunc : Relationship (optional), which could be fairly long, in which
case the line wraps here.
thirdfunc, fourthfunc, fifthfunc
numpy.array : relationship (optional)
numpy.ndarray : Relationship (optional), which could be fairly long, in
which case the line wraps here.
numpy.dot, numpy.linalg.norm, numpy.eye

Notes
-----
Expand Down
46 changes: 46 additions & 0 deletions doc/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,52 @@ numpydoc_attributes_as_param_list : bool
as the Parameter section. If it's False, the Attributes section will be
formatted as the Methods section using an autosummary table.
``True`` by default.
numpydoc_xref_param_type : bool
Whether to create cross-references for the parameter types in the
``Parameters``, ``Other Parameters``, ``Returns`` and ``Yields``
sections of the docstring.
``False`` by default.

.. note:: Depending on the link types, the CSS styles might be different.
consider overridding e.g. ``span.classifier a span.xref`` and
``span.classifier a code.docutils.literal.notranslate``
CSS classes to achieve a uniform appearance.

numpydoc_xref_aliases : dict
Mappings to fully qualified paths (or correct ReST references) for the
aliases/shortcuts used when specifying the types of parameters.
The keys should not have any spaces. Together with the ``intersphinx``
extension, you can map to links in any documentation.
The default is an empty ``dict``.

If you have the following ``intersphinx`` namespace configuration::

intersphinx_mapping = {
'python': ('https://docs.python.org/3/', None),
'numpy': ('https://docs.scipy.org/doc/numpy', None),
...
}

The default ``numpydoc_xref_aliases`` will supply some common ``Python``
standard library and ``NumPy`` names for you. Then for your module, a useful
``dict`` may look like the following (e.g., if you were documenting
:mod:`sklearn.model_selection`)::

numpydoc_xref_aliases = {
'LeaveOneOut': 'sklearn.model_selection.LeaveOneOut',
...
}

This option depends on the ``numpydoc_xref_param_type`` option
being ``True``.
numpydoc_xref_ignore : set
Words not to cross-reference. Most likely, these are common words
used in parameter type descriptions that may be confused for
classes of the same name. For example::

numpydoc_xref_ignore = {'type', 'optional', 'default'}

The default is an empty set.
numpydoc_edit_link : bool
.. deprecated:: edit your HTML template instead

Expand Down
27 changes: 21 additions & 6 deletions numpydoc/docscrape_sphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sphinx.jinja2glue import BuiltinTemplateLoader

from .docscrape import NumpyDocString, FunctionDoc, ClassDoc
from .xref import make_xref

if sys.version_info[0] >= 3:
sixu = lambda s: s
Expand All @@ -37,6 +38,9 @@ def load_config(self, config):
self.use_blockquotes = config.get('use_blockquotes', False)
self.class_members_toctree = config.get('class_members_toctree', True)
self.attributes_as_param_list = config.get('attributes_as_param_list', True)
self.xref_param_type = config.get('xref_param_type', False)
self.xref_aliases = config.get('xref_aliases', dict())
self.xref_ignore = config.get('xref_ignore', set())
self.template = config.get('template', None)
if self.template is None:
template_dirs = [os.path.join(os.path.dirname(__file__), 'templates')]
Expand Down Expand Up @@ -79,11 +83,17 @@ def _str_returns(self, name='Returns'):
out += self._str_field_list(name)
out += ['']
for param in self[name]:
param_type = param.type
if param_type and self.xref_param_type:
param_type = make_xref(
param_type,
self.xref_aliases,
self.xref_ignore)
if param.name:
out += self._str_indent([named_fmt % (param.name.strip(),
param.type)])
param_type)])
else:
out += self._str_indent([unnamed_fmt % param.type.strip()])
out += self._str_indent([unnamed_fmt % param_type.strip()])
if not param.desc:
out += self._str_indent(['..'], 8)
else:
Expand Down Expand Up @@ -158,10 +168,8 @@ def _process_param(self, param, desc, fake_autosummary):

prefix = getattr(self, '_name', '')
if prefix:
autosum_prefix = '~%s.' % prefix
link_prefix = '%s.' % prefix
else:
autosum_prefix = ''
link_prefix = ''

# Referenced object has a docstring
Expand Down Expand Up @@ -213,8 +221,15 @@ def _str_param_list(self, name, fake_autosummary=False):
parts = []
if display_param:
parts.append(display_param)
if param.type:
parts.append(param.type)
param_type = param.type
if param_type:
param_type = param.type
if self.xref_param_type:
param_type = make_xref(
param_type,
self.xref_aliases,
self.xref_ignore)
parts.append(param_type)
out += self._str_indent([' : '.join(parts)])

if desc and self.use_blockquotes:
Expand Down
19 changes: 18 additions & 1 deletion numpydoc/numpydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
raise RuntimeError("Sphinx 1.0.1 or newer is required")

from .docscrape_sphinx import get_doc_object
from .xref import DEFAULT_LINKS
from . import __version__

if sys.version_info[0] >= 3:
Expand Down Expand Up @@ -154,7 +155,11 @@ def mangle_docstrings(app, what, name, obj, options, lines):
app.config.numpydoc_show_inherited_class_members,
'class_members_toctree': app.config.numpydoc_class_members_toctree,
'attributes_as_param_list':
app.config.numpydoc_attributes_as_param_list}
app.config.numpydoc_attributes_as_param_list,
'xref_param_type': app.config.numpydoc_xref_param_type,
'xref_aliases': app.config.numpydoc_xref_aliases,
'xref_ignore': app.config.numpydoc_xref_ignore,
}

cfg.update(options or {})
u_NL = sixu('\n')
Expand Down Expand Up @@ -218,6 +223,7 @@ def setup(app, get_doc_object_=get_doc_object):

app.setup_extension('sphinx.ext.autosummary')

app.connect('builder-inited', update_config)
app.connect('autodoc-process-docstring', mangle_docstrings)
app.connect('autodoc-process-signature', mangle_signature)
app.connect('doctree-read', relabel_references)
Expand All @@ -230,6 +236,9 @@ def setup(app, get_doc_object_=get_doc_object):
app.add_config_value('numpydoc_class_members_toctree', True, True)
app.add_config_value('numpydoc_citation_re', '[a-z0-9_.-]+', True)
app.add_config_value('numpydoc_attributes_as_param_list', True, True)
app.add_config_value('numpydoc_xref_param_type', False, True)
app.add_config_value('numpydoc_xref_aliases', dict(), True)
app.add_config_value('numpydoc_xref_ignore', set(), True)

# Extra mangling domains
app.add_domain(NumpyPythonDomain)
Expand All @@ -239,6 +248,14 @@ def setup(app, get_doc_object_=get_doc_object):
'parallel_read_safe': True}
return metadata


def update_config(app):
"""Update the configuration with default values."""
for key, value in DEFAULT_LINKS.items():
if key not in app.config.numpydoc_xref_aliases:
app.config.numpydoc_xref_aliases[key] = value


# ------------------------------------------------------------------------------
# Docstring-mangling domains
# ------------------------------------------------------------------------------
Expand Down
Loading