Skip to content

Instantly share code, notes, and snippets.

@mallamanis
Created April 30, 2020 19:44
Show Gist options
  • Save mallamanis/972ff8b7f1b898afdc0b4e0e3e76202f to your computer and use it in GitHub Desktop.
Save mallamanis/972ff8b7f1b898afdc0b4e0e3e76202f to your computer and use it in GitHub Desktop.
Use dict.items() instead of explicitly accessing the values within the loop.
/**
* @name Iterate of the items of a dictionary using `.items()`.
* @description instead of iterating over the keys of a dictionary and the indexing the dictionary,
use `.items()` to retrieve the key-value pairs.
* @kind problem
* @tags maintainability
* @problem.severity recommendation
* @sub-severity low
* @precision medium
* @tags speed
* @sub-severity low
* @id py/use-for-items
*/
import python
from For loop, Name dict
where
loop.getIter() = dict and
dict.pointsTo().getClass().getQualifiedName() = "dict" and
exists(Subscript subs |
loop.getBody().contains(subs) and
subs.getValue().(Name).pointsTo(dict.pointsTo()) and
subs.getIndex().(Name).getVariable() = loop.getTarget().(Name).getVariable() and
// The dict[val] is *not* only assigned directly.
not exists(AugAssign assignment | assignment.contains(subs) and assignment.getTarget() = subs) and
not exists(AssignStmt assignment | assignment.contains(subs) and assignment.getATarget() = subs)
)
select dict, "Use `.items()` to jointly iterate over the values of each `" + loop.getTarget().(Name).getVariable().getId()
+ "` in the dictionary `" + dict.getId() + "` instead of indexing the dictionary again."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment