Nathan Fellman Nathan Fellman - 6 months ago 48
Python Question

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

Is it possible to forward-declare a function in Python? I want to sort a list using my own

cmp
function before it is declared.

print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])


I've organized my code to put the definition of
cmp_configs
method after the invocation. It fails with this error:

NameError: name 'cmp_configs' is not defined


Is there any way to "declare"
cmp_configs
method before it's used? It would make my code look cleaner?

I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem. However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion. If you don't like this example, assume that I have a case in which it's really necessary to forward declare a function.

Consider this case where forward-declaring a function would be necessary in Python:

def spam():
if end_condition():
return end_result()
else:
return eggs()

def eggs():
if end_condition():
return end_result()
else:
return spam()


Where
end_condition
and
end_result
have been previously defined.

Is the only solution to reorganize the code and always put definitions before invocations?

Answer

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.

Comments