In my script I have four functions that work like this:
def function_four():
# Does Stuff
function_one()
def function_three():
# Does Stuff
function_two()
def function_one():
usr_input = input("Options: '1') function_three | '2') Quit\nOption: ")
if usr_input == '1':
function_three()
elif usr_input == '2':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
def function_two():
usr_input = input("Options: '1') function_four | '2') function_three | '3') Quit\nOption: ")
if usr_input == '1':
function_four()
elif usr_input == '2':
function_three()
elif usr_input == '3':
sys.exit()
else:
print("Did not recognise command. Try again.")
function_one()
I need to know if this will cause the problem I think it will: the functions never closing, causing lots of open functions (and, presumably, wasted memory and eventual slow-down) to appear, never to disappear until the user quits the script. If true, then this would most likely be bad practise and inadvisable, meaning that there must be an alternative?
Whenever you have Python code that is:
you are almost always better off replacing the recursive call with a loop. In this case the recursion is completely unnecessary, probably wastes resources and arguably makes the code harder to follow.
edit: Now that you’ve posted the code, I’d suggest recasting it as a state machine. The following page provides a summary of Python modules that could be useful: link.
Even without any additional modules, your code lends itself to a simple non-recursive rewrite:
Note that the functions no longer call each other. Instead, each of them returns the next function to call, and the top-level loop takes care of the calling.