Skip to content

bad-builtin-groupby (ODW8155)

Preview (since 0.16.2.2) · Related issues · View source

Derived from the odoo linter.

Fix is sometimes available.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks for use of itertools.groupby.

Why is this bad?

itertools.groupby only groups consecutive runs, which is a frequent footgun. Prefer odoo.tools.groupby, which sorts first.

Example

import itertools

itertools.groupby(records, key=lambda r: r.partner_id)

Use instead:

from odoo.tools import groupby

groupby(records, key=lambda r: r.partner_id)

Fix safety

The fix rewrites the call to odoo.tools.groupby, importing it if necessary. It is marked as unsafe because the two functions are not interchangeable: odoo.tools.groupby sorts the whole input first and returns a list of (key, list) pairs, where itertools.groupby lazily yields one group per consecutive run. Code that relied on the consecutive-run behavior, or on the groups being iterators, changes meaning.