flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

B031 flagged on non-itertools groupby

Open eachimei opened this issue 2 years ago • 3 comments

Recent B031 addition: https://github.com/PyCQA/flake8-bugbear/pull/347

A code that defines a groupby function (not itertools.groupby) will still raise B031 error.

Example:

def groupby(x, y):
    return dict().items()


for _, v in groupby(None, None):
    if v:
        ...
    if v:
        ...

Then:

$ flake8 example.py
example.py:8:8: B031 Using the generator returned from `itertools.groupby()` more than once will do nothing on the second usage. Save the result to a list, if the result is needed multiple times.

flake8: 6.0.0, flake8-bugbear: 23.2.13

Perhaps we can have a better inspection so the error is not raised in such cases?

eachimei avatar Feb 15 '23 08:02 eachimei

Just noting B905 has the same issue for zip.

If many people define their own groupby I wonder if the rule should be off by default 🤷‍♂️

malthejorgensen avatar Feb 15 '23 10:02 malthejorgensen

I guess it's not that common and I was "lucky" enough 😅... funny thing is, I wanted a non-generator variant of groupby (that also doesn't require a sorted input) so created one for my project, and then CI errored out on flake8 and hence reported this issue...

eachimei avatar Feb 15 '23 11:02 eachimei

Anyway, I refactored my code (renamed the utility). Not a big problem since it's an internal (private) utility.

eachimei avatar Feb 15 '23 11:02 eachimei