sourcery-ai / sourcery

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

Faulty for-append-to-extend refactoring #279

Closed yairchu closed 1 year ago

yairchu commented 1 year ago

Checklist

Description

The following snippet:

    for x in gen:
        (less if x < pivot else more).append(x)

Gets a buggy suggestion to change into:

    (less if x < pivot else more).extend(iter(gen))

The problem lies with the LHS being appended not being constant and relying on the iterated x.

Debug Information

IDE Version: VS Code 1.71.1

Sourcery Version: Sourcery 0.12.7

Operating system and Version: maxOS 12.5

Appendix

Example code snippet in context:

def quick_sort(gen):
    """
    Haskell-style leet lazy evaluation quick_sort.
    It doesn't need to fully sort everything to find the N smallest elements.

    An example use case is iterating over potential dates by the order of their attractiveness,
    until one of them agrees to date you (no need to iterate over the rest after a match is found),
    but be warned that the odds of that may be lower if you're using functions like this one.

    The complexity would be O(N*log(K)) where K is the ammount iterated,
    in comparison to O(N*log(N)) for the full sorting algorithm.
    """
    gen = iter(gen)
    try:
        pivot = next(gen)
    except StopIteration:
        return
    less = []
    more = []
    for x in gen:
        (less if x < pivot else more).append(x)
    yield from quick_sort(less)
    yield pivot
    yield from quick_sort(more)
Hellebore commented 1 year ago

Thanks for raising! Will look into a fix.

Hellebore commented 1 year ago

This fix is now merged and will be in the next release.

Hellebore commented 1 year ago

Fixed with 0.12.9