Sphinx autodoc if Python method moved to Rust PyO3

62 Views Asked by At

If I have a Python module and a method:

# mymod.py
def func(x):
    """
    Return a value.
    """
    return x

And a Sphinx autodocument command in an rst file:

API Ref
-------

.. automodapi:: project.mymod

This will generate relevant pages and cross-referencable links for :meth:'project.mymod.func'. All is well and good!

However, If I now create a Rust extension for my Python package and move this function to Rust and build the extension with PyO3 I can maintain code backwards compatibility by importing the rust function to the Python module as an overload:

// mymod.rs
#[pymethod]
fn func(x: T) -> PyResult<T> {
    Ok(x)
}
# mymod.py
from mymodrs import func

Sphinx will now no longer auto detect this func method, with no cross-referencable link. Can I add something to maintain the Sphinx operability? I don't mind if it is manual.

1

There are 1 best solutions below

0
Attack68 On

One way I have found so far of getting this to work with almost the same formatting and section consistency is to do something like:

Current Version


# mymod.py
def func(x):
    """
    Return a value

    Parameters
    ----------
    x: float
        The value

    Returns
    -------
    float
    """
    return x
# index.rst
Methods
-------

.. automodapi:: project.mymod

New Rust Version

# mymod.py
from mymodrs import func

func.__doc__ = "Return a value"  # Needed for the description in autosummary

Create an explicit documentation file for the Rust method.

# api_manual/mymod.func.rst
func
----

.. currentmodule:: mymod

.. py:method:: func(x)

   Return a value

   :param x: The value
   :param type: float

   :rtype: float

Link to it in the original automod file.

# index.rst
Methods
-------

.. autosummary::
   mymod.func

.. toctree::
   :titlesonly:
   :maxdepth: 0
   :hidden:

   api_manual/mymod.func.rst