using identifiers before they are defined

Evan Driscoll driscoll at cs.wisc.edu
Tue Jun 12 14:33:31 EDT 2012


On 01/-10/-28163 01:59 PM, Julio Sergio wrote:
> I know that changing the order of the definitions will work, however there are
> situations in which referring to an identifier before it is defined is
> necessary, e.g., in crossed recursion.

Mutual recursion isn't a problem: the following strange expression of 
factorial works fine:

def strange_helper(x):
     return factorial(x)

def factorial(x):
     if x==0:
         return 1
     else:
         return x * strange_helper(x-1)

print factorial(5)


The reason is names are never looked up when the parser sees them, but 
rather only when execution reaches them. So the fact that 'factorial' 
hasn't been defined yet when the parser is dealing with 'strange_helper' 
is fine, because when 'strange_helper' is actually *called*, 'factorial' 
has been defined.

Here's another example to illustrate, in a different manner that doesn't 
use this "undefined" thing:

def foo():
     print "Inside the first version of foo"

def call_foo():
     foo()

call_foo()

def foo():
     print "Inside the second version of foo"

call_foo()

This prints:
  Inside the first version of foo
  Inside the second version of foo


Evan



More information about the Python-list mailing list