Created
April 30, 2020 19:44
-
-
Save mallamanis/972ff8b7f1b898afdc0b4e0e3e76202f to your computer and use it in GitHub Desktop.
Use dict.items() instead of explicitly accessing the values within the loop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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