B035: False positive for comprehensions that use a walrus operator
Daverball opened this issue · comments
by_payment = {
payment_id: charge
for charge in charges
if (payment_id := charge.metadata.get('payment_id')) is not None
}
This results in a B035, even though payment_id
is definitely not a static value, it's derived from the individual charge
object.
I'm not surprised this wasn't caught, because comprehensions and if expressions are some of the few exceptions where the use of a variable can occur before its definition, so it requires special casing when looking up names.
So the error is in in this section of the check
elif isinstance(node.key, ast.Name):
if node.key.id not in self._get_dict_comp_loop_var_names(node):
self.errors.append(
B035(node.key.lineno, node.key.col_offset, vars=(node.key.id,))
)
Instead of only looking for the loop variable names in the target
node it also needs to look for any ast.NamedExpr
within the ifs
nodes of each ast.comprehension
.