Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid syntax errors when rewriting str(dict) in f-strings #5538

Merged
merged 1 commit into from
Jul 5, 2023
Merged
Changes from all commits
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
4 changes: 4 additions & 0 deletions crates/ruff/resources/test/fixtures/ruff/RUF010.py
Original file line number Diff line number Diff line change
@@ -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
@@ -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;
};

Original file line number Diff line number Diff line change
@@ -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;
};

Original file line number Diff line number Diff line change
@@ -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;
}

Original file line number Diff line number Diff line change
@@ -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 |