Skip to content

B909 misses dict.keys() deletion #16865

Open
@skairunner

Description

@skairunner

Summary

Using this file:

import typing as t

d: t.Dict[str, int] = {
    "a": 1,
    "b": 2,
}

for key in d.keys():
    del d[key]

When I run this command:

ruff check --preview --select B909 testruff.py

I expect to see a B909 failure, but instead all tests pass. I feel like B909 should be able to catch this, especially because running this code raises a RuntimeError:

RuntimeError: dictionary changed size during iteration

For what it's worth, flake8-bugbear also fails to catch this problem.

Modifying the test code to this causes Ruff to correctly point out the B909 error:

import typing as t

d: t.Dict[str, int] = {
    "a": 1,
    "b": 2,
}

for key in d:
    del d[key]

Version

ruff 0.11.0 (2cd25ef 2025-03-14)

Metadata

Metadata

Assignees

No one assigned

    Labels

    previewRelated to preview mode featuresruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions