Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF065.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,16 @@ def str(s): return f"str = {s}"
info("Hex: %s", hex(42))
log(logging.INFO, "Hex: %s", hex(255))

# Test cases for str() that should NOT be flagged (issue #21315)
# str() with no arguments - should not be flagged
logging.warning("%s", str())

# str() with multiple arguments - should not be flagged
logging.warning("%s", str(b"\xe2\x9a\xa0", "utf-8"))

# str() with starred arguments - should not be flagged
logging.warning("%s", str(*(b"\xf0\x9f\x9a\xa7", "utf-8")))

# str() with keyword unpacking - should not be flagged
logging.warning("%s", str(**{"object": b"\xf0\x9f\x9a\xa8", "encoding": "utf-8"}))

Original file line number Diff line number Diff line change
Expand Up @@ -138,16 +138,25 @@ pub(crate) fn logging_eager_conversion(checker: &Checker, call: &ast::ExprCall)
.zip(call.arguments.args.iter().skip(msg_pos + 1))
{
// Check if the argument is a call to eagerly format a value
if let Expr::Call(ast::ExprCall { func, .. }) = arg {
if let Expr::Call(ast::ExprCall {
func,
arguments: str_call_args,
..
}) = arg
{
let CFormatType::String(format_conversion) = spec.format_type else {
continue;
};

// Check for various eager conversion patterns
match format_conversion {
// %s with str() - remove str() call
// Only flag if str() has exactly one non-starred positional argument and no keyword arguments
FormatConversion::Str
if checker.semantic().match_builtin_expr(func.as_ref(), "str") =>
if checker.semantic().match_builtin_expr(func.as_ref(), "str")
&& str_call_args.args.len() == 1
&& !str_call_args.args[0].is_starred_expr()
&& str_call_args.keywords.is_empty() =>

Choose a reason for hiding this comment

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

logging.warning("%s", str(object="!")), with one keyword argument, should still be flagged.

{
checker.report_diagnostic(
LoggingEagerConversion {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,4 +216,6 @@ RUF065 Unnecessary `hex()` conversion when formatting with `%s`. Use `%#x` inste
69 | info("Hex: %s", hex(42))
70 | log(logging.INFO, "Hex: %s", hex(255))
| ^^^^^^^^
71 |
72 | # Test cases for str() that should NOT be flagged (issue #21315)
|