Consider the following structure
main_func()
{
sub_func1()
sub_func2()
sub_func3()
.
.
.
sub_funcN()
exit()
}
I wish to implement a 'go-back to previous function' functionality while keeping the sequence of execution intact.
For example: During execution of main function, the user selected 'go-back to previous function' in sub_func3() to go to sub_func2() and then continue the same sequence of the main program i.e sub_func2() -> sub_func3 () -> .... -> sub_funcN() -> exit() How can this be achieved?
Looking forwards to your response
CodePudding user response:
There might be a better way to handle this depending on the actual use case, but one idea is to have each sub_func
return a flag indicating whether to advance to the next function or rewind to the previous one, and then use that to move an index through a list:
def sub_func1() -> int:
if input("Go back? ") == "y":
return -1
# do other stuff
return 1
sub_funcs = [
sub_func0,
sub_func1,
sub_func2,
sub_func3,
# ...
sub_funcN
]
i = 0
while i < len(sub_funcs):
i = sub_funcs[i]()
A variation on this might be to have the sub_funcs raise a GoBack
exception that is caught by a try/except
in the caller to decrement the index, with the default being to increment it (that way each function doesn't need to explicitly return 1
in order to advance the state machine).
CodePudding user response:
You can create a Class (let's call it OperationClass). main() function creates an instance of OperationClass.
On OperationClass you also define the operation flow, back() and next() methods().
So you can make your main() function call OperatorClass.next() or OperatorClass.back(), and this methods knows the flow and what function (methods) is supposed to be executed