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"
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With