sourcery-ai / sourcery

Instant AI code reviews
https://sourcery.ai
MIT License
1.53k stars 66 forks source link

set-comprehension false positive on attribute #271

Closed ronnodas closed 1 year ago

ronnodas commented 2 years ago

Checklist

Description

When defining a set attribute by using add in a loop, set-comprehension triggers even when there are conditionals involving the set being added to. The equivalent refactoring does not appear for defining variables. Here is some code sample:

class Symmetrizer:
    def __init__(self, pairs):
        self.unordered_pairs = set()
        for x, y in pairs:
            if (y, x) not in self.unordered_pairs:
                self.unordered_pairs.add((x,y))

Symmetrizer({(1, 2), (3, 4), (2, 1)})

The suggested refactoring is to replace the __init__ body by:

self.unordered_pairs = {(x, y) for x, y in pairs if (y, x) not in self.unordered_pairs}

which raises an AttributeError.

Debug Information

IDE Version: PyCharm Professional Edition 2022.2.1

Sourcery Version: Sourcery 0.12.7

Operating system and Version: Linux, Fedora 36

ruancomelli commented 2 years ago

Hello, @ronnodas! Thank you for reporting this bug. I was able to reproduce it and will work on a fix. We will let you know once it is fixed.

ruancomelli commented 2 years ago

Hi, @ronnodas! A fix for this bug has just been merged. It will be available in the next Sourcery release. Thanks again for reporting this issue!

Hellebore commented 1 year ago

Resolved in 0.12.8

Hellebore commented 1 year ago

Resolved in 0.12.8