too simple a question : forward declaration?

Alex Martelli aleax at aleax.it
Wed May 14 04:08:00 EDT 2003


<posted & mailed>

Helmut Jarausch wrote:

> Sorry for this super simple question,
> but I haven't found an answer in my
> Python reference "Python in a nutshell"
> which I like very much.

Oops!  Sorry, I just didn't think of mentioning
this specific issue in the Nutshell.


> How can I do a forward declaration of a function
> like in C, i.e. just the defining header
> without the body.

You cannot.  Python has no declarations, just
executable statements.  Having no declarations,
it has, in particular, no FORWARD declarations.


> E.g. the following doesn't work because
> of the lack of such a forward declaration
> 
> Test();  # error  Test unknown
> 
> def Test():
>    print "hello test"
> 
> Of course this is a trivial example and I could
> of course put the function declaration before the
> first call, but that's ugly for longer scripts.

The correct solution, particularly for longer scripts,
is to keep as the script's top-level statements just
about only function definitions (def statements) [as
well as a few others such as class statements and, if
you need them, bindings of initial values to global
data names, of course].

In particular, code the actual logic of the script in
a function traditionally named 'main'.  I.e. the
above would be coded as:

def main():
    Test()    # no silly redundant semicolons please

def Test():
    print 'hello test'


Then, at the very end of your script, put the traditional
and idiomatic snippet:

if __name__ == '__main__':
    main()


Your module's __name__ is set to string '__main__' when
the module is run as the main script, but not when it is
imported by some OTHER module.  This way, you get to use
your script as a main program when you want, and ALSO to
import it from other scripts in order to reuse the various
functionalities that the script packages into functions.

This idiom is mentioned in the Nutshell on p. 122, in
section "The Main Program".  However, in that section I
did not explicitly explain that one way to exploit that
idiom is to put the script's "top-level functionality"
into a function traditionally named 'main'; sorry!


Alex





More information about the Python-list mailing list