Is there a way to do more work after a return statement?

You could still do some work after return if you return from a try-block, the finally-block would still be executed, e.g.:

def fun(x):
    try:
        return x * 20
    finally:
        print("Yay! I still got executed, even though my function has already returned!")

print(fun(5))

Expected Output:

Yay! I still got executed, even though my function has already returned!
100

Quoting the docs:

When return passes control out of a try statement with a finally
clause, that finally clause is executed before really leaving the
function.

Leave a Comment