Search code examples
pythonpython-3.xfunctionreturn

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.


Solution

  • 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