sourcery icon indicating copy to clipboard operation
sourcery copied to clipboard

Faulty for-append-to-extend refactoring

Open yairchu opened this issue 3 years ago • 1 comments

Checklist

  • [X] I have searched the Sourcery documentation for the issue, and found nothing
  • [X] I have checked there are no open bugs referencing the same bug or problem

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)

yairchu avatar Sep 14 '22 14:09 yairchu

Thanks for raising! Will look into a fix.

Hellebore avatar Sep 14 '22 14:09 Hellebore

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

Hellebore avatar Sep 22 '22 10:09 Hellebore

Fixed with 0.12.9

Hellebore avatar Sep 28 '22 19:09 Hellebore