8

I have this problem all the time that I want to write a docstring like this:

def foo(arg):
   '''Add ``arg`` to the list of :class:`foo.bar.baz.Argument`s.'''
   pass

However, that doesn't work, Sphinx will warn that

py:class reference target not found: foo.bar.baz.Argument`s

so it's treating the s after the closing backtick as part of the class name. This does not happen with e.g. punctuation marks like the dot .. Is there anything to be done about this, except adding a space between the class name and the Plural-s (which looks crazy)?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
oarfish
  • 4,116
  • 4
  • 37
  • 66

2 Answers2

12

You should be able to use backslash-escaped whitespace.

def foo(arg):
   '''Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\ s.'''
   pass
mzjn
  • 48,958
  • 13
  • 128
  • 248
  • 1
    I had been using the above, but newer python versions are giving a deprecation warning that `\ ` is an invalid escape sequence. Is there a new way to do this? – youngmit Feb 03 '21 at 23:58
  • @youngmit: Cannot reproduce. It works for me with Python 3.9.1 and Sphinx 3.4.3. However, there have been changes to the treatment of escape sequences (see https://stackoverflow.com/a/52335971/407651). Does it work with two backslashes or a raw string? – mzjn Feb 04 '21 at 06:02
  • 2
    I was able to get it to work by just using a single backslash, but add an `r` prefix. This way, sphinx still gets the `\ ` escape sequence and interprets it properly, but python ignores it. – youngmit Feb 09 '21 at 15:14
0

Similar to the answer of @mzjn, but in recent versions of Python you have to include two backslashes, e.g.:

def foo(arg):
   """Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\\ s."""

As pointed out before, a raw string ("r-string") also does the job with one backslash:

def foo(arg):
   r"""Add ``arg`` to the list of :class:`foo.bar.baz.Argument`\ s."""
Felix D.
  • 786
  • 1
  • 11
  • 17