Skip to content

loop-iterator-mutation (B909) - logic to determine whether the mutation is followed by a break statement is incorrect #12402

@DetachHead

Description

@DetachHead

the rule seems to check whether or not the loop has a break after the mutation, because that makes the mutation safe:

items = [1, 2, 3]

for item in items:
    items.append(item) # no error
    break

however i've noticed two issues with this logic:

  1. it doesn't seem to account for when there's another statement between the mutation and the break:

    items = [1, 2, 3]
    
    for item in items:
        items.append(item)
        if True:
            pass
        break # error

    this should still be considered safe, because the statement does not effect the flow of the loop at all.

  2. if there's a continue statement followed by a break statement, it does not report an error, even though the mutation is unsafe:

    items = [1, 2, 3]
    
    for item in items:
        items.remove(item)
        continue
        break

playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingruleImplementing or modifying a lint rule

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions