Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward-declare/prototype a function in Python? [duplicate]

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

//PROTOTYPE
do python protoyping

writeHello() //GIVES ERROR AS IT WAS NOT DEFINED YET

def writeHello():
    print "Hello"
like image 670
George Cloone-y Avatar asked Aug 16 '14 14:08

George Cloone-y


People also ask

Can you forward declare functions in Python?

You can't forward-declare a function in Python. If you have logic executing before you've defined functions, you've probably got a problem anyways.

How do you prototype a function in Python?

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.

What is difference between function prototype and forward declaration?

A function prototype is a declaration statement that includes a function's name, return type, and parameters. It does not include the function body. What is a forward declaration? A forward declaration tells the compiler that an identifier exists before it is actually defined.


1 Answers

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.

like image 92
Martijn Pieters Avatar answered Oct 04 '22 20:10

Martijn Pieters