Are circular dependencies possible in Python?
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Sat Apr 9 19:51:15 EDT 2005
In <IEosBE.GtB at bath.ac.uk>, Tim Tyler wrote:
> Like C, Python seems to insist I declare functions before calling
> them - rather than, say, scanning to the end of the current script
> when it can't immediately find what function I'm referring to.
They don't have to be declared but to be *defined* in Python before you
can call them. A ``def`` is executed in Python -- a function object is
given a name. The content of a Python script is executed in the order the
code is written.
> C lets you predeclare functions to allow for the existence of
> functions with circular dependencies.
>
> Does Python allow you to do something similar?
Yes, just define the function before it gets actually called::
def func_a(n):
if n > 5:
return
else:
func_b(n + 1)
def func_b(n):
print n
func_a(n + 1)
func_a(0)
What happens here is
1. Define function A. That function B doesn't exist by now is no problem
because it is not called yet. There's just the instruction to call it if
the body of function A is executed. *Then* function B has to exist.
2. Define function B. You can swap both definitions without problems.
3. Function A is actually called and *must* exist at this point.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list