How do I forward-declare a function to avoid `NameError`s for functions defined later?

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 work properly.

The general rule in Python is that a function should be defined before its usage, which does not necessarily mean it needs to be higher in the code.

Leave a Comment