Don't trigger SIM401 for complex default values (#1825)

Resolves #1809.
This commit is contained in:
Charlie Marsh
2023-01-12 12:51:23 -05:00
committed by GitHub
parent c6320b29e4
commit bbc1e7804e
2 changed files with 26 additions and 2 deletions

View File

@@ -79,3 +79,9 @@ if key in a_dict:
else:
var2 = value2
var = "default"
# OK (complex default value)
if key in a_dict:
var = a_dict[key]
else:
var = foo()

View File

@@ -2,7 +2,8 @@ use rustpython_ast::{Cmpop, Constant, Expr, ExprContext, ExprKind, Stmt, StmtKin
use crate::ast::comparable::ComparableExpr;
use crate::ast::helpers::{
contains_call_path, create_expr, create_stmt, has_comments, unparse_expr, unparse_stmt,
any_over_expr, contains_call_path, create_expr, create_stmt, has_comments, unparse_expr,
unparse_stmt,
};
use crate::ast::types::Range;
use crate::checkers::ast::Checker;
@@ -257,7 +258,7 @@ pub fn use_dict_get_with_default(
if orelse_var.len() != 1 {
return;
};
let ExprKind::Compare { left: test_key, ops , comparators: test_dict } = &test.node else {
let ExprKind::Compare { left: test_key, ops , comparators: test_dict } = &test.node else {
return;
};
if test_dict.len() != 1 {
@@ -284,6 +285,23 @@ pub fn use_dict_get_with_default(
return;
}
// Check that the default value is not "complex".
if any_over_expr(default_val, &|expr| {
matches!(
expr.node,
ExprKind::Call { .. }
| ExprKind::Await { .. }
| ExprKind::GeneratorExp { .. }
| ExprKind::ListComp { .. }
| ExprKind::SetComp { .. }
| ExprKind::DictComp { .. }
| ExprKind::Yield { .. }
| ExprKind::YieldFrom { .. }
)
}) {
return;
}
let contents = unparse_stmt(
&create_stmt(StmtKind::Assign {
targets: vec![create_expr(expected_var.node.clone())],