Non-iterable used in for loopΒΆ
ID: py/non-iterable-in-for-loop
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- quality
- reliability
- correctness
Query suites:
- python-code-quality.qls
- 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.