Calling functions before that are def'ed

Peter Hansen peter at engcorp.com
Mon Sep 22 19:19:39 EDT 2003


Daniel Dittmar wrote:
> 
> Charles Larry wrote:
> > Is there a way to define functions after the main part of a Python
> > script?
> >
> > Example:
> >
> > #!/usr/local/bin/python
> >
> > # this code yields a NameError
> >
> > print_message("hello world")
> >
> > def print_message(msg):
> >     print msg
> 
> #!/usr/local/bin/python
> 
> def main ():
>      print_message("hello world")
> 
> def print_message(msg):
>      print msg
> 
> if __name__ == "__main__":
>      main ()
> 
> def statements are really executable statements and not declarations, so
> the order is important.

Note that the above slightly changes the behaviour of the code when globals
are involved.  Putting the original code directly under the __main__ part
at the end, however, does not.  (This example is too simple to exhibit any
difference in behaviour, but the following is the "safer" method for the 
unwary newbie, even if it's not as clean in the long run.)

def print_message(msg):
    print msg

if __name__ == "__main__":
    print_message("hello world")

-Peter




More information about the Python-list mailing list