2
votes

Sphinx is great at linking to specific Python objects.

For example, writing

:func:`foo.bar`

will link directly to the bar function in foo.py. I want this same functionality but, instead of creating a clickable link, I want it to be the code of bar(), instead.

The .. code-block:: language directive requires you to manually write the code that you want to add. But I want to link to code that already exists in external Sphinx projects using intersphinx, not write the code myself. :mod:, :func:, and others only create links, not actually include source-code.

There's also .. literalinclude:: filename but in my case, I can't use it because the function comes from outside of the Sphinx project (It's being linked using intersphinx and isn't part of the actual project). Even if .. literalinclude:: filename could somehow work cross-project, I think that I'd still need to use :lines: to filter every function down, which would be a huge pain to keep track of.

How can refer to a function / class by its namespace path and use that to add its source-code directly into the sphinx rst file? (Not as a clickable link, but the literal code).

2

2 Answers

1
votes

This feature is available out of the box. What you are looking for is the literalinclude directive and its :pyobject: argument.

---[mymodule.py]------------
def hello(who):
    print(f'Hello {who} !')


---[mydocumentation.rst]----

Bla bla bla lorem ipsum

.. literalinclude: ../../path/to/mymodule.py
   :pyobject: hello

This will only include the code of the hello() function in your documentation.