Skip to content
7 changes: 7 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF027_0.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,10 @@ def fuzz_bug():
def backslash_test():
x = "test"
print("Hello {'\\n'}{x}") # Should not trigger RUF027 for Python < 3.12

# Test case for comment handling in f-string interpolations
# Should not trigger RUF027 for Python < 3.12 due to comments in interpolations
def comment_test():
x = "!"
print("""{x # }
}""")
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,12 @@ fn should_be_fstring(
for f_string in value.f_strings() {
let mut has_name = false;
for element in f_string.elements.interpolations() {
// Check if the interpolation expression contains backslashes
// F-strings with backslashes in interpolations are only valid in Python 3.12+
// Check if the interpolation expression contains backslashes or comments
// F-strings with backslashes or comments in interpolations are only valid in Python 3.12+
let interpolation_text = &fstring_expr[element.range()];
if target_version < PythonVersion::PY312 && interpolation_text.contains('\\') {
if target_version < PythonVersion::PY312
&& (interpolation_text.contains('\\') || interpolation_text.contains('#'))
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Number signs are only problematic when they would start comments. f"{'#'}" is fine in Python 3.11.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! Updated the check to use a has_comment_hash() helper that tracks string nesting — # inside a nested string literal (e.g., f"{'#'}") is now correctly recognized as not a comment.

return false;
}

Expand Down
Loading