Skip to content

Prevent usage of return, yield in try/finally #8260

@hofrob

Description

@hofrob

Current problem

Code in finally blocks will always be executed. If there's a return inside the try, it's possible to overwrite this return value with a return in the finally.

def add(a: int, b: int) -> int:
    try:
        return a + b
    finally:
        return 0


if __name__ == "__main__":
    print(add(1, 2))  # those args will be ignored; "0" is printed

Desired solution

There should not be any return or yield statements in a finally block.

Additional context

https://docs.python.org/3/reference/compound_stmts.html#finally-clause

The return value of a function is determined by the last return statement executed.

Metadata

Metadata

Assignees

Labels

CheckersRelated to a checkerEnhancement ✨Improvement to a componentGood first issueFriendly and approachable by new contributors

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions