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

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.

Leave a Comment