How do I reference a documented Python function parameter using Sphinx markup?

25,449

Solution 1

I've just built an extension to accomplish this task. So far it seems to be working with standalone HTML build and additionally with readthedocs (after some more tweaks).

the extension is available at: https://pypi.python.org/pypi/sphinx-paramlinks/.

I'm rolling it out right now for the Alembic and SQLAlchemy projects. (sample).

I take disagreement with the suggestion that linking to params means the docs are too lengthy. The Python standard library is a poor example here as stdlib functions are necessarily granular and simple. Software that is accomplishing a more coarse-grained task, where a single function rides on top of a complex problem to be solved, will often have parameters that require a lot more explanation; this explanation is often quite valuable as the solution to a particular problem elsewhere, and therefore being able to link to it is very important.

Solution 2

There is no simple way to get a direct reference to a parameter of a function with sphinx and I don't know an extension for this problem.

The documentation of the python domain explains which objects can be cross referenced.

A possible way to give the user a reference to parameter bar of function foo would be

See parameter ``bar`` in :func:`foo`.

Maybe a direct reference would be possible by writing an extension.

Solution 3

For those, that want to use sphinx-paramlinks with sphinx.ext.napoleon here is a patch. Simple find the right fragment in the sphinx-paramlinks source code (sphinx_paramlinks\sphinx_paramlinks.py, somewhere around line 50) and replace it with this:

def cvt(m):
    directive, modifier, objname, paramname = (
        m.group(1), m.group(2) or '', name, m.group(3))
    if directive == 'param':
        refname = _refname_from_paramname(paramname, strip_markup=True)
        item = ('single', '%s (%s parameter)' % (refname, objname),
                '%s.params.%s' % (objname, refname), '')
        if LooseVersion(__version__) >= LooseVersion('1.4.0'):
            item += (None,)
        doc_idx.append(item)
    return ":%s %s_sphinx_paramlinks_%s.%s:" % (
        directive, modifier, objname, paramname)
return re.sub(r'^:(param|type) ([^:]+? )?([^:]+?):', cvt, line)

Note: remember about the right indent.

I'm not a Sphinx specialist, but this seems to get the job done.

Share:
25,449

Related videos on Youtube

Inactivist
Author by

Inactivist

Eclectic programmer. (Re)Discovering Python. Loving it. Some things I'm working on: WhatEvah: Discover Twitter Influencers for your choice of search terms. Twitter-Streamer: Python-based utility using Twitter's Streaming API. Capture Twitter streams with minimal fuss. What you do with it is up to you. Sylvestr Eats Tweets: Realtime stats for various things mentioned on Twitter. Uses a variant of Twitter-Streamer to capture Twitter's Streaming API data. WhoPlussed: Google+ app to view top commenters on a Google+ post.

Updated on July 09, 2022

Comments

  • Inactivist
    Inactivist almost 2 years

    I'd like to reference a previously-documented function parameter elsewhere in a Python docstring. Consider the following (admittedly completely artificial) example:

    def foo(bar):
        """Perform foo action
        :param bar: The bar parameter
        """
    
        def nested():
            """Some nested function that depends on enclosing scope's bar parameter.
            I'd like to reference function foo's bar parameter here
            with a link, is that possible?"""
            return bar * bar
    
        # ...
        return nested()
    

    Is there a simple way to embed a parameter reference using Sphinx markup, or will this happen automagically?

    (I'm a complete Sphinx newbie. I've been scanning the Sphinx docs and haven't found an answer to this question, or an example demonstrating proper markup.)

  • Inactivist
    Inactivist about 12 years
    Perhaps my original question/example was overly simplistic. (That's what happens when I post questions in a sleep-deprived state :D) I've updated the question and code example to help clarify my motivation.
  • orome
    orome over 10 years
    This is great, but doesn't appear to work with Googly docstrings (such as those used with sphinxcontrib.napoleon). Is that something that could be made to work?
  • zzzeek
    zzzeek over 10 years
    depends on how it works. If it rewrites the params straight to restructured text, sphinx-paramlinks wouldn't really have much to offer that out of the box, as it relies upon parsing the raw RST before sphinx gets control of it. This is largely to avoid having to manipulate the internals of sphinx. it would be much much much better if Sphinx just implemented this feature natively at this point. I'm hoping my extension makes it obvious how desperately needed this feature is.
  • orome
    orome over 10 years
    Thanks. I expected something like that (it makes sense). And I agree with you that this is a desperately needed feature.
  • Hibou57
    Hibou57 almost 10 years
    I installed with pip, and trying it, I get this error from Sphinx: Could not import extension sphinx-paramlinks (exception: No module named 'sphinx-paramlinks'), while pip list says it's installed. I'm using Python 3.4.
  • Hibou57
    Hibou57 almost 10 years
    OK, I got it. The package's name is sphinx-paramlinks but the extension's name to be added to conf.py is sphinx_paramlinks (underscore vs dahs).
  • orome
    orome over 8 years
    Love this, but which it worked with Googly docstrings. Any chance of that (now that some time has passed)?
  • orome
    orome over 8 years
    Also: this give import errors when I try to build on Read The Docs (No module named sphinx_paramlinks).
  • maxkoryukov
    maxkoryukov almost 7 years
    Doesn't work properly with :type paramname: int -- eats my type definitions without warnings... Sphinx (sphinx-build) 1.6.3