Calling functions before that are def'ed

Michael Geary Mike at DeleteThis.Geary.com
Mon Sep 22 17:45:41 EDT 2003


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
>
> I know functions can be put in separate files and imported, but I want
> everything in a single file.  Am I stuck with defining all the
> functions first?  If so, how come at compile-time Python can't look
> ahead in the program and discover the existence of functions referred
> to but not yet defined?

Function definitions are executable statements, so like any other statement
they are executed in the order they are encountered.

If you prefer the style of having functions after your main program, simply
define a main function at the top of your script, and call it at the end.

-Mike






More information about the Python-list mailing list