no-range-loop-with-len

Try in Playground
python-best-practicesBest PracticeWarning

0

No tags

No CWE or CVE

Do not iterate over an array using for in range(len(array)). Use instead for i in array.

Ast Rule: for loop


no-range-loop-with-len

How to write a rule
function visit(node, filename, code) {
  if(node.list && node.list.str) {
    const pattern =  /range\(\s*len\(\s*([a-zA-Z0-9]+)\s*\)/;
    const found = node.list.str.match(pattern);
    if (found && found.length === 2){
      const forcode = code.substring(node.statements.startIndex, node.statements.stopIndex);

      const listname = found[1];
      const forVariable = node.variables[0].atom.str;

      const toReplace = `${listname}\[${forVariable}\]`;

      const newCodeInsideFor = forcode.replaceAll(toReplace, forVariable);
      console.log("====");
      console.log(newCodeInsideFor);
      console.log("====");
      const replaceListEdit = buildEditUpdate(node.list.start.line, node.list.start.col, node.list.end.line, node.list.end.col, listname);
      const replaceForContentEdit = buildEditUpdate(node.statements.start.line, node.statements.start.col, node.statements.end.line, node.statements.end.col, newCodeInsideFor);
      const fix = buildFix("use the list directly", [replaceForContentEdit, replaceListEdit]);
      const error = buildError(node.list.start.line, node.list.start.col, node.list.end.line, node.list.end.col, `do not use range(len(${listname}))`, "INFO", "BEST_PRACTICE");
      addError(error.addFix(fix));
    }

  }

}

use-range-len.py

Expected test result: has error

for i in range(len(tab)):
  bla(   tab[i]   )

iterate-over-values.py

Expected test result: no error

for i in tab:
  bla(   i   )
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Explore
  • Cookbooks
  • Playground
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.