SIGN IN SIGN UP
astral-sh / ruff UNCLAIMED

An extremely fast Python linter and code formatter, written in Rust.

0 0 40 Rust

[`flake8-comprehensions`] Document `RecursionError` edge case in `__len__` (`C416`) (#25286)

C416's autofix rewrites a list comprehension like `[item for item in
self]` into `list(self)`, but when the original is reached from inside
`__len__`, the rewrite recurses: CPython's `list()` constructor probes
`__length_hint__` (which dispatches to `__len__`) as a sizing
optimization while iterating, so `list(self)` from inside `__len__`
calls `__len__` again. The same applies to `dict()` and `set()` calls on
`self`.

In #13752, MichaReiser noted that extending the docs would be reasonable
and that detecting this control flow isn't the goal. I added a paragraph
to the C416 docstring with a runnable example of the failure mode, plus
the `# noqa: C416` workaround for when the comprehension is reached
(directly or transitively) from `__len__`.

The change is docstring-only. `cargo dev generate-all` and `uvx prek run
--from-ref main` both pass.

fixes https://github.com/astral-sh/ruff/issues/13752

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
A
Aditya Singh committed
ba87ab5d33c3c5190014ac3e70be19a122cbb065
Parent: ceca602
Committed by GitHub <noreply@github.com> on 5/21/2026, 8:36:23 PM