Skip to content Skip to sidebar Skip to footer

How To Force A Function To Exit After Calling Another Function?

I have two functions each calling the other on their final line as a means of passing control. Is there an elegant way to force one function to exit before the other gets executed,

Solution 1:

If you want one function to exit before the other is called, you will have to actually exit the function instead of having it call the other one:

deff1(x):
    print('f1', x)
    return f2, (x+1,)
deff2(x):
    print('f2', x)
    return f1, (x+1,)

f, args = f1, (0,)
whileTrue:
    f, args = f(*args)

This will require that external control structure you wanted to avoid.


As an aside, the way you're trying to make function calls work is a lot like GOTO, and can end up having the same effects on program complexity and maintainability.

Solution 2:

The easiest way would be to set a condition in your function in order to terminate/stop the recursion.

It could be something like this:

deff1(x):
if x == 30:           #Set a limit in order to just print, without callingprint("f1", x)
else:
    print("f1",x)
    f2(x+1)

deff2(x):
    print("f2",x)
    f1(x+1)

f1(0)

Solution 3:

Simple solution

You could just add an if statement:

deff1(x):
    print("f1", x)
    if x <= 30:
        f2(x+1)

deff2(x):
    print("f2",x)
    if x <= 30:
        f1(x+1)

Long answer

The answer to if you can force the function to quit before calling the next function is no-ish. Specifically you are asking for a tail-recursion optimization which python does not optimize.

Solution 4:

As user2357112 has pointed out, I'm not sure why you would want to do this.

However, if you really have to do this then you can assign a boolean value to the function to indicate that it has been called already.

deff1(x):
    print("f1",x)
    f1.called = Trueifnot f2.called:
        f2(x+1)

deff2(x):
    print("f2",x)
    f2.called = Trueifnot f1.called:
        f1(x+1)

f1(0)

Post a Comment for "How To Force A Function To Exit After Calling Another Function?"