I want to do something like this in Python. I took out what we are really doing and replaced it with this ridiculous example that will really never end. Please assume the calls from a<==>b are finite. Our code does have the logic to end the cycle.
I am worried that I will get an error for calling b in a before b is defined. However, I read that as long as I don’t make a call that executes a before def b then I should have no problem. What is the real answer here? And what is python doing behind the scenes to make it not exit on line 2 (b())
def a():
b()
def b():
a()
b()
The real answer is that
binside the definition ofawill be looked up in the module scope and similarly forainside the definition ofb. Sinceaandbboth exist in the module scope after both definitions have been processed, your mutual recursion will work.(It will stop working if the names
aandbare shadowed inside the function definitions, but I assume you’ll manage to avoid that.)See this question for an overview of Python scoping rules.