Skip to content

match_docstring_end matches too much, making I002 introduce a syntax error #19159

@dscorbett

Description

@dscorbett

Summary

When multiple string-only statements appear at the top of a module, class, or function definition, only the first is the docstring, but match_docstring_end matches them all. That makes the fix for missing-required-import (I002) insert required imports after all the string-only statements, not immediately after the docstring. That is usually harmless but it introduces a syntax error when the required import is a future import. Example:

$ cat >i002.py <<'# EOF'
"docstring"
"not a docstring"
print(f"{__doc__=}")
# EOF

$ python i002.py
__doc__='docstring'

$ ruff --isolated check --config 'lint.isort.required-imports=["from __future__ import annotations"]' i002.py --select I002 --fix
Found 1 error (1 fixed, 0 remaining).

$ cat i002.py
"docstring"
"not a docstring"
from __future__ import annotations
print(f"{__doc__=}")

$ python i002.py 2>&1 | tail -n 1
SyntaxError: from __future__ imports must occur at the beginning of the file

Version

ruff 0.12.2 (9bee837 2025-07-03)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions