astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
29.06k stars 947 forks source link

escape-sequence-in-docstring (D301) reports escaped docstrings within docstrings #12152

Open tjkuson opened 1 week ago

tjkuson commented 1 week ago

Running

ruff check --isolated --select D301

on

def foo():
    """
    This docstring contains another docstring.

        def bar():
            \"\"\"Here it is!\"\"\"
    """

returns an escape-sequence-in-docstring (D301) diagnostic, printing

example.py:2:5: D301 Use `r"""` if any backslashes in a docstring
  |
1 |   def foo():
2 |       """
  |  _____^
3 | |     This docstring contains another docstring.
4 | |
5 | |         def bar():
6 | |             \"\"\"Here it is!\"\"\"
7 | |     """
  | |_______^ D301
  |
  = help: Add `r` prefix

However, adding the r prefix and removing the backslashes is a syntax error:

def foo():
    r"""
    This docstring contains another docstring.

        def bar():
            """Here it is!"""
    """

Docstrings in within docstrings can appear when a docstring contains a code snippet (which is how I discovered the issue). I would expect D301 not to be raised, as making the docstring raw doesn't work.

Ruff version 0.5.0

Search terms: D301, backslash, escape

Update: managed to reproduce with

def foo():
    """
    This docstring contains another docstring.

        def bar():
            \"""Here it is!\"""
    """

as well.

ukyen8 commented 1 week ago

Hi, I would like to work on this issue. Is anyone already working on it?

dhruvmanila commented 1 week ago

@ukyen8 I don't think so, go for it!