5

I am writing documentations for a python package with a clear_stop_character function, in which users can provide extra stop-chars in a list. In the documentation I have written:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\\*']).
"""

It is crucial for the users to see the double backslash before the stop-char. However, the help() outcome of the built package shows:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\*']).
"""

So, it will be misleading for the users.
BTW, I did not find a solution based on the previous questions.
Any ideas?

maaniB
  • 595
  • 6
  • 23
  • 1
    Does this answer your question? [Why doesn't Python auto escape '\' in \_\_doc\_\_?](https://stackoverflow.com/questions/33734170/why-doesnt-python-auto-escape-in-doc) – python_user Jun 06 '21 at 03:02
  • @python_user yes, it does. But, I think the next answer is also good. Maybe this record help the others. – maaniB Jun 06 '21 at 03:10
  • 1
    https://peps.python.org/pep-0257/#:~:text=quotes%22%22%22%20around%20docstrings.-,Use,-r%22%22%22raw%20triple – Andrew Sep 30 '22 at 18:45

1 Answers1

4

\ in Python is an escape character which tells Python to interpret the character following it literally. This means that \\ tells Python to interpret the second \ literally, thus causing the error where the first backslash is not displayed.

The simplest solution to this problem is to use four backslashes: \\\\. This way, Python sees the first backslash and interprets the second one literally, printing \. Then, the third backslash will tell Python to interpret the fourth one literally like \.

Simply rewrite your code as:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\\\\*']).
"""
q9i
  • 205
  • 2
  • 11
  • And now the docstring itself is wrong when a user looks at the source file, how is this a good solution? – bugmenot123 Jul 14 '23 at 14:27
  • 1
    Typically docstrings are used to generate documentation pages for source code; any time the `__doc__` object is accessed, it will not have the four backslashes but only two, so any user-facing docs will always look correct. The source file will still have four backslashes, but this is an unavoidable consequence of backslash being used as an escape character. – q9i Jul 19 '23 at 18:56