pythonfunction-prototypes

How can I forward-declare/prototype a function in Python?


How do I prototype a method in a generic Python program similar to C++?

# Prototype
# Do Python prototyping

writeHello() # Gives an error as it was not defined yet

def writeHello():
    print "Hello"

Solution

  • Python does not have prototyping because you do not need it.

    Python looks up globals at runtime; this means that when you use writeHello the object is looked up there and then. The object does not need to exist at compile time, but does need to exist at runtime.

    In C++ you need to prototype to allow two functions to depend on one another; the compiler then can work out that you are using the second, later-defined function. But because Python looks up the second function at runtime instead, no such forward definition is needed.

    To illustrate with an example:

    def foo(arg):
        if not arg:
            return bar()
    
    def bar(arg=None):
        if arg is not None:
            return foo(arg)
    

    Here, both foo and bar are looked up as globals when the functions are called, and you do not need a forward declaration of bar() for Python to compile foo() successfully.