Возврат из родительской функции в дочернюю функцию - PullRequest
3 голосов
/ 01 апреля 2020

Я знаю, что в функции вы можете выйти из функции, используя return,

def function():
    return

, но вы можете выйти из родительской функции из дочерней функции?

Пример:

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")


Я пытался поднять Exception, как подсказывает этот ответ , но это просто завершает всю программу.

Ответы [ 2 ]

3 голосов
/ 01 апреля 2020

Вы можете вызвать исключение из exit_both, а затем перехватить то, куда вы звоните function, чтобы предотвратить выход из программы. Здесь я использую пользовательское исключение, так как не знаю подходящего встроенного исключения, и нужно избегать перехвата Exception.

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")

Вывод:

This is the parent function
This is the child function
This should still be able to print
0 голосов
/ 01 апреля 2020

Одним из решений может быть следующее:

returnflag = False
def function():
    global returnflag
    print("This is the parent function")

    def exit_both():
        global returnflag
        print("This is the child function")
        returnflag = True
        return

    exit_both()
    if returnflag == True:
        return
    print("This shouldn't print")

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

Или, если вам не нравится играть с глобальными переменными, вы можете попробовать это:

def function():
    returnflag = False
    # or you can use function.returnflag = False -> the result is the same
    print("This is the parent function")

    def exit_both():
        print("This is the child function")
        function.returnflag = True
        return

    exit_both()
    if function.returnflag == True:
        return
    print("This shouldn't print")

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