Non-iterable used in for loop¶
ID: py/non-iterable-in-for-loop
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- correctness
- types
Query suites:
- python-security-and-quality.qls
Click to see the query in the CodeQL repository
The for
statement is designed to allow you to iterate over the elements of a sequence or other iterable object. If a non-iterable object is used in a for
statement (for var in object:
) then a TypeError will be raised.
Recommendation¶
Since this defect usually indicates a logical error, it is not possible to give a general method for addressing the defect.
Example¶
In this example, the loop may attempt to iterate over None
, which is not an iterable. It is likely that the programmer forgot to test for None
before the loop.
def illegal_for_loop(seq = None):
for x in seq:
print (x)
References¶
Python Language Reference: The for statement, object.iter.
Python Standard Library: Iterator types.
Scipy lecture notes: Iterators, generator expressions and generators.