21

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"
5
  • 3
    Just define writeHello() before calling it. There is no such thing as 'prototyping' in Python. Why do you think you need it? Commented Aug 16, 2014 at 14:38
  • 2
    I like to define my function at the bottom of the program, a habit from Java and C++. I wanted to know if there was a way to prototype in Python. Commented Aug 16, 2014 at 14:40
  • 4
    @GeorgeClone-y This feature just does not make sense in Python. This is because Python method definitions are just code that is executed (and thus must be executed prior to being resolved/invoked); in Java and C++ the methods are compiled to a meta-structure. Commented Aug 16, 2014 at 14:41
  • 3
    @GeorgeClone-y: Then you have to put all remaining code into a main-function and call main() in the last line of your program. Commented Aug 16, 2014 at 15:12
  • Modern Python has type annotations/hints and stub files (.pyi). Commented Jun 14, 2022 at 17:22

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.