Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing forward declarations for functions in Python [duplicate]

Tags:

python

c

function

Is it possible to declare functions and implement them separately in python ? I mean something like in C :

void foo();



void foo() 
{

}
like image 339
Noam Avatar asked Feb 26 '26 04:02

Noam


2 Answers

C forward declarations are used to work around dependency problems. Function foo is used by function bar, and foo needs bar to exist before you can declare it:

void bar()
{
    if (condition) { foo(); }
}

void foo() 
{
    if (condition) { bar(); }
}

won't compile because foo hasn't been declared yet; void foo(); is the C spelling for I know what I am doing, compiler, accept that foo will exist later.

There are no such dependency problems in Python, as global names are looked up at runtime; they don't have to yet exist at compile time.

In other words, this just works:

def bar():
    if condition: foo()

def foo():
    if condition: bar()

because bar and foo are resolved at runtime.

like image 191
Martijn Pieters Avatar answered Feb 28 '26 18:02

Martijn Pieters


If your script is standalone you can use __name__=='__main__' to circumvent your problem with forward declaration read more.

Note that this is not really an answer to your question but a work around. Consider the following script as an example.

def main():
    bar()

def bar(): 
    print "Hello World"

if __name__=="__main__":
   main() # can be any function not necessarily "main"
like image 44
Sigve Karolius Avatar answered Feb 28 '26 16:02

Sigve Karolius