0

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()
Jake
  • 4,134
  • 2
  • 16
  • 20
  • Why don't you just try this out? If you really don't want the hassle of dealing with this on your local machine, try it on http://ideone.com. – Marcin Mar 13 '12 at 11:13
  • I did test it out. I apparently forgot to add the part about why does it work. I edited it. – Jake Mar 13 '12 at 11:16
  • @Jake: I don't get the last sentence of your edit. Why would the script exit at line 2? – Fred Foo Mar 13 '12 at 11:18
  • b() doesn't exist yet. Why doesn't python throw a bit about use of an undefined function? Your answer is wonderful and explains it, but is it unreasonable that I expected that behavior? – Jake Mar 13 '12 at 11:19
  • Also, to the vote down, any reason? I am fairly sure this isn't a copy. To someone who doesn't know the guts of python the answer to this question could be helpful. c users for instance might be expecting the ability to prototype – Jake Mar 13 '12 at 11:23

2 Answers2

3

The real answer is that b inside the definition of a will be looked up in the module scope and similarly for a inside the definition of b. Since a and b both exist in the module scope after both definitions have been processed, your mutual recursion will work.

(It will stop working if the names a and b are shadowed inside the function definitions, but I assume you'll manage to avoid that.)

See this question for an overview of Python scoping rules.

Community
  • 1
  • 1
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

This will work fine, upto a recursion depth of 1000 calls. It depends on what you're using it for as to whether this is an issue or not.

Check doing a search on recursive functions to find out more...

fraxel
  • 34,470
  • 11
  • 98
  • 102