[EMAIL PROTECTED] wrote:

> As a bit of a [python] newbie myself, the proper procedure for forward
> declaring things has so far evaded me as well.
>
> Is there a "right" way to do this in python? :
> ...
>
> def f1( i ):
>   if( i < 20 ): return f2(i)
>   else: return 0
>
> def f2( i ):
>   if( i > 20 ): return f1(i)
>   else: return 0

This code will work just fine.

The trick to remember, is that the def statement is an executable statement.
The def statement for any function must be run by the interpreter, before the
function can be called.  But the interpreter doesn't look up names until
runtime, so you can use the *name* of the function before you define it --
it's all dependent on the order that the interpreter processes things.

In the code above, when this file is run/imported, the interpreter will read
through this, see the def statements, and create two function objects.
Later, when you actually call f1(5), the interpreter steps throught the body
of f1(), sees that the argument passes the if-test, then sees the name f2.
At this point, the interpreter does a name-lookup to find what f2 is bound
to.  If the interpreter hadn't already seen 'def f2(i): ...', then we'd get
the NameError now.  In this case, it sees "oh, yes, I have this function
that's named f2..." and proceeds to call the function.

Hope this makes things clearer...  :)

Jeff Shannon
Technician/Programmer
Credit International


_______________________________________________
ActivePython mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to