PyCQA / flake8-bugbear

A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.
MIT License
1.06k stars 104 forks source link

B038 false positive in 24.1.15 + 24.1.16 #451

Closed mikaelarguedas closed 8 months ago

mikaelarguedas commented 8 months ago

First of all thanks for this new B038 new rule, it's a great addition!

Using flake8-bugbear 24.1.15

The following code is flagged.

some_list = [1, 2, 3]
for elem in some_list:
    print(elem)
    if elem == 2:
        found_idx = some_list.index(elem)  # should not error
        break

Although a method of some_list is called I believe this doesn't have any effect on the mutable

mikaelarguedas commented 8 months ago

cc @mimre25 for feedback on this as it may also impact the ruff implementation

wxtim commented 8 months ago

Looks similar to

mydicts = {'a': {'foo': 1, 'bar': 2}}

for mydict in mydicts:
    if mydicts.get('a', ''):
        print(mydict['foo'])

B038 is complaining about any instance of an object method called inside the loop that object is the iterator for, without checking whether the loop is modifying it.

cooperlees commented 8 months ago

Agree this looks a bad / annoying false positive. Will take a fix for this asap and release.

Thanks for reporting.

mimre25 commented 8 months ago

Oh snap, I actually ran this on a quite big code-base as a test and I didn't have any false positives reported.

I'll take a look and see if I can fix this.

Thanks for reporting this and tagging me :slightly_smiling_face:

Skrethel commented 8 months ago

I've also encountered this false positive for copy() function

d = {}
for _ in d:
    copied = d.copy()