Search code examples
python-3.xpython-sphinxrestructuredtext

Displaying a portion of the link caption in reStructuredText


I am an absolute beginner in reStructuredText and Sphinx for Python documentation. I am giving it a try on one of my existing scripts, an Emailer class that handles creating/sending email messages, which uses Python's email library. My docstring (in NumPy style, I believe) for one of its methods is as follows:

def attach(self, msg: EmailMessage, file: BinaryIO, /, *, filename: Optional[str] = None, **kwargs) -> None:
        """Add an attachment to the :class:`~email.message.EmailMessage` msg using specified params.

        Parameters
        ----------
        msg: :class:`~email.message.EmailMessage`
            The message to add the attachment to.
        file: :class:`~typing.BinaryIO`
            The file-like object of the attachment to be added, opened in binary mode.
        filename: Optional[:class:`str`]
            The name to use for the attachment. Defaults to ``None``, using ``file.name``.
        **kwargs
            Additional kwargs that would be passed to :meth:`~email.message.EmailMessage.add_attachment`.
        """

My question is, how do I make it so that the description for **kwargs shows up as:

Additional kwargs that would be passed to EmailMessage.add_attachment()

The ~ operator makes it so that only add_attachment() shows up, and if I use :meth:EmailMessage.add_attachment, a link fails to generate at all (apparently I need to specify the full origin email.message.<foo>?)

As a side, I would appreciate some pointers on syntax/convention. For example, should I remove the type hints in my method signature, considering they are already described in the docstring? Also, how do I exclude certain attributes/methods from showing up in the resulting documentation? Thanks.


Solution

  • The following markup works:

    :meth:`EmailMessage.add_attachment() <email.message.EmailMessage.add_attachment>`
    

    From https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#cross-referencing-syntax:

    You may supply an explicit title and reference target, like in reST direct hyperlinks:
    :role:`title <target>` will refer to target, but the link text will be title.

    "Direct hyperlinks" are described here: https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html?highlight=hyperlinks#external-links.