return-in-finally / W0134ΒΆ

Message emitted:

'return' shadowed by the 'finally' clause.

Description:

Emitted when a 'return' statement is found in a 'finally' block. This will overwrite the return value of a function and should be avoided.

Problematic code:

def second_favorite():
    fruits = ["kiwi", "pineapple"]
    try:
        return fruits[1]
    finally:
        # because of this `return` statement, this function will always return "kiwi"
        return fruits[0]  # [return-in-finally]

Correct code:

def second_favorite():
    fruits = ["kiwi", "pineapple"]
    try:
        return fruits[1]
    except KeyError:
        ...

    return fruits[0]

Related links:

Created by the basic checker.