python.lang.correctness.dict-modify-iterating.dict-del-while-iterate

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
141,169
Download Count*

It appears that $DICT[$KEY] is a dict with items being deleted while in a for loop. This is usually a bad idea and will likely lead to a RuntimeError: dictionary changed size during iteration

Run Locally

Run in CI

Defintion

rules:
  - id: dict-del-while-iterate
    message: "It appears that `$DICT[$KEY]` is a dict with items being deleted while
      in a for loop. This is usually a bad idea and will likely lead to a
      RuntimeError: dictionary changed size during iteration"
    metadata:
      references:
        - https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    languages:
      - python
    severity: WARNING
    pattern-either:
      - pattern: |
          for $KEY, $VALUE in $DICT.items():
              ...
              del $DICT[$KEY]
      - pattern: |
          for $KEY in $DICT.keys():
              ...
              del $DICT[$KEY]

Examples

dict-modify-iterating.py

d = {'a': 1, 'b': 2}
# ruleid:dict-del-while-iterate
for k,v in d.items():
    del d[k]

d = {'a': 1, 'b': 2}
# ruleid:dict-del-while-iterate
for k in d.keys():
    del d[k]

# ruleid:dict-del-while-iterate
for k in d.keys():
    print(d[k])
    del d[k]

# ok:dict-del-while-iterate
for k in d.keys():
    print(d[k])
    x = d[k]