def

Martijn Faassen m.faassen at vet.uu.nl
Tue Aug 22 12:54:52 EDT 2000


Matthew Schroeder <MSchroeder at creativesolutions.com> wrote:
> Is there some way to define the funtions at the end of the module (.py
> file)?

> I'm used to having the functions defined at the end of the file, then at the
> top of the file is where the functions are actually called.

Probably we cannot do what you're asking for, which I interpret as something 
like this:

foo()

def foo():
    print "foo!"

This won't work, as at the point you try to call 'foo', the function foo
has not yet been defined, as it definition statement (def foo()) has
not yet been executed by the interpreter. The other way around does
work:

def foo():
    print "foo!"

foo()

But, you don't want this, really (famous comp.lang.python maneuver). Instead,
you want to place those calls in the main() (or otherwise named) function
of your module, in anything but the most trivial of scripts:

def main()
    foo()

def foo():
    print "foo!"

Of course, if you run this module, nothing happens. You can fix this
by placing a call to main at the bottom (just that single call,
nothing more):

def main():
    foo()

def foo():
    print "foo!"

main()

But, you still don't want this usually, for the same reason you didn't want
the original solution: if you place code in the top-level of the module,
you can only use that module to execute it, and you cannot properly
import it anymore; as soon as you do that the first time, the top-level
code would get executed, which wouldn't be what you want.

Instead, the standard recommendation is to use this:

def main():
    foo()

def foo():
    print "foo!"

if __name__ == "__main__":
    main()

The latter magic incantation checks if the global variable '__name__' is
the string "__main__". This is only the case if the module is being
executed directly by Python, not when it's imported by another module.
This way, your main() function only gets executed when you actually 
execute your module, and you can still use the module's functionality
in other programs through import, without problems.

In the case when there is no plausible main() function for your module
(it is a library), you can provide a self-test function instead. Instead
of having a main() and calling that, you have a test().

Of course for trivial scripts all this is unnecessary. The only advantage of
this strategy there is allows you to order your code in any order you want,
without having to worry about whether names are defined yet (but just
calling main() at the bottom would accomplish this already).

Hope this helps.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list