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?
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.