Skip to content

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

Closed
@tjkuson

Description

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.

Metadata

Assignees

Labels

bugSomething isn't workingdocstringRelated to docstring linting or formattinghelp wantedContributions especially welcomeruleImplementing or modifying a lint rule

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions