Inactivist Inactivist - 10 months ago 64
Python Question

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

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.)

Answer Source

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:

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.