Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from parent function in a child function

I know in a function you can exit the function using return,

def function():
    return

but can you exit a parent function from a child function?

Example:

def function()
    print("This is the parent function")

    def exit_both():
        print("This is the child function")
        # Somehow exit this function (exit_both) and exit the parent function (function)

    exit_both()
    print("This shouldn't print")

function()
print("This should still be able to print")


I tried raising an Exception, as this answer suggests, but that just exits the whole program.

like image 295
DYD Avatar asked Sep 18 '25 20:09

DYD


1 Answers

You can raise an exception from exit_both, then catch that where you call function in order to prevent the program being exited. I use a custom exception here as I don't know of a suitable built-in exception and catching Exception itself is to be avoided.

class MyException(Exception):
    pass

def function():
    print("This is the parent function")

    def exit_both():
        print("This is the child function")
        raise MyException()

    exit_both()
    print("This shouldn't print")

try:
    function()
except MyException:
    # Exited from child function
    pass
print("This should still be able to print")

Output:

This is the parent function
This is the child function
This should still be able to print
like image 111
dspencer Avatar answered Sep 21 '25 11:09

dspencer