I want to sort a list using my own cmp
function. For the purpose of this discussion we can use the following example which is equivalent to what I'm trying to do:
print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])
However, because of the way I organized my code, I much prefer to put the definition of cmp_configs
after the sort. However, I fail on:
NameError: name 'cmp_configs' is not defined
Is there any way to "declare" cmp_configs
before it's used, which will make my code cleaner, or do I have to define it only before?
Note: 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.
Edit: A case in which may be necessary is:
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.
But now I understand that since spam
and eggs
are called inside functions then by the time I call either one of them both of them will already have been defined, so the only solution is in fact to reorganize the code.