Skip to content

Commit

Permalink
Avoid syntax errors when rewriting str(dict) in f-strings (#5538)
Browse files Browse the repository at this point in the history
Closes #5530.
  • Loading branch information
charliermarsh authored Jul 5, 2023
1 parent c5bfd1e commit 5a74a8e
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 3 deletions.
4 changes: 4 additions & 0 deletions crates/ruff/resources/test/fixtures/ruff/RUF010.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,7 @@ def ascii(arg):
" intermediary content "
f" that flows {repr(obj)} of type {type(obj)}.{additional_message}" # RUF010
)


# OK
f"{str({})}"
8 changes: 7 additions & 1 deletion crates/ruff/src/rules/pylint/rules/type_bivariance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,13 @@ impl Violation for TypeBivariance {

/// PLC0131
pub(crate) fn type_bivariance(checker: &mut Checker, value: &Expr) {
let Expr::Call(ast::ExprCall { func,args, keywords, .. }) = value else {
let Expr::Call(ast::ExprCall {
func,
args,
keywords,
..
}) = value
else {
return;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,13 @@ pub(crate) fn type_param_name_mismatch(checker: &mut Checker, value: &Expr, targ
return;
};

let Expr::Call(ast::ExprCall { func, args, keywords, .. }) = value else {
let Expr::Call(ast::ExprCall {
func,
args,
keywords,
..
}) = value
else {
return;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,20 @@ pub(crate) fn explicit_f_string_type_conversion(
};

// Can't be a conversion otherwise.
if args.len() != 1 || !keywords.is_empty() {
if !keywords.is_empty() {
continue;
}

// Can't be a conversion otherwise.
let [arg] = args.as_slice() else {
continue;
};

// Avoid attempting to rewrite, e.g., `f"{str({})}"`; the curly braces are problematic.
if matches!(
arg,
Expr::Dict(_) | Expr::Set(_) | Expr::DictComp(_) | Expr::SetComp(_)
) {
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,5 +243,7 @@ RUF010.py:35:20: RUF010 [*] Use explicit conversion flag
35 |- f" that flows {repr(obj)} of type {type(obj)}.{additional_message}" # RUF010
35 |+ f" that flows {obj!r} of type {type(obj)}.{additional_message}" # RUF010
36 36 | )
37 37 |
38 38 |


0 comments on commit 5a74a8e

Please sign in to comment.