sourcery icon indicating copy to clipboard operation
sourcery copied to clipboard

Lift return into if can result in unnecessary else after return

Open avylove opened this issue 4 years ago • 2 comments

Issue description or question

For the following code

def elapsed(self):

    if self.count == self.total:
        elapsed = self.last_update - self.start
    else:
        elapsed = time.time() - self.start

    return elapsed

Sourcery suggests "lift return into if":

def elapsed(self):

    if self.count == self.total:
        return self.last_update - self.start
    else:
        return time.time() - self.start

But this will trigger R1705: Unnecessary "else" after "return" (no-else-return) in Pylint. The correct form in this case should be.

def elapsed(self):

    if self.count == self.total:
        return self.last_update - self.start
    return time.time() - self.start

Sourcery Version

0.8.7

Code editor or IDE name and version

VSCode 1.53.0

OS name and version

Linux

avylove avatar Feb 13 '21 16:02 avylove

This is one of the Pylint codes I don't quite see eye to eye with, but you're right - we shouldn't be triggering new warnings. I will look into addressing this.

Hellebore avatar Feb 15 '21 08:02 Hellebore

I see it as a case of a guard clause. Therefore I don't put else before returns. But PEP8 show both cases in the return example. So that's on you to decide

marcoaaguiar avatar Mar 10 '21 14:03 marcoaaguiar