Is it possible to forward-declare a function in Python? Is it possible to forward-declare a function in Python? python python

Is it possible to forward-declare a function in Python?


What you can do is to wrap the invocation into a function of its own.

So that

foo()def foo():    print "Hi!"

will break, but

def bar():    foo()def foo():    print "Hi!"bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.


If you kick-start your script through the following:

if __name__=="__main__":   main()

then you probably do not have to worry about things like "forward declaration". You see, the interpreter would go loading up all your functions and then start your main() function. Of course, make sure you have all the imports correct too ;-)

Come to think of it, I've never heard such a thing as "forward declaration" in python... but then again, I might be wrong ;-)


If you don't want to define a function before it's used, and defining it afterwards is impossible, what about defining it in some other module?

Technically you still define it first, but it's clean.

You could create a recursion like the following:

def foo():    bar()def bar():    foo()

Python's functions are anonymous just like values are anonymous, yet they can be bound to a name.

In the above code, foo() does not call a function with the name foo, it calls a function that happens to be bound to the name foo at the point the call is made. It is possible to redefine foo somewhere else, and bar would then call the new function.

Your problem cannot be solved because it's like asking to get a variable which has not been declared.