[Tutor] defining functions [if __name__ == '__main__']

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 10 Dec 2001 11:10:30 -0800 (PST)


On Mon, 10 Dec 2001 alan.gauld@bt.com wrote:

> > Gang, in some languages you MUST define somethign before 
> > using it, in others no, as long as it is defined 

Here's an example that shows how to get it so you can call functions in
the order you want:

###
## testmain1.py
def main():
    sayFirstVerse()
    print "For the rain, it raineth every day"

def sayFirstVerse():
    print "Hey, ho, the wind and the rain"

main()
###


There are two important parts to this:

    1.  Put our main part of our program in a separate function.  Because
it's a function, it's somewhat inactive.  We're only telling Python what
it looks like, but also asking to hold off calling it until we ask for it.

    2.  Put a statement at the very bottom of our program that calls that
main() function, which gets things started.


This trick should help avoid the kind of ordering problems that you might
have with your program.


[Side note below.]

By the way, there's a variation of this that Python programmers can use
when they're writing modules.  It looks like this:

###
## testmain2.py
def main():
    sayFirstVerse()
    print "For the rain, it raineth every day"

def sayFirstVerse():
    print "Hey, ho, the wind and the rain"

if __name__ == '__main__':          ## Here's the important part.
    main()
###

The difference between this and the above example is that, in this case,
main() will not get called if we 'import' testmain2 as a module.  If we
run testmain2.py directly:

###
[dyoo@tesuque dyoo]$ python testmain2.py 
Hey, ho, the wind and the rain
For the rain, it raineth every day
###

But, if we're already in Python, we can 'import' testmain2 and use it as
if it were a toolbox of stuff:

###
>>> import testmain2
>>> dir(testmain2)
['__builtins__', '__doc__', '__file__', '__name__', 'main',
'sayFirstVerse']
>>> testmain2.sayFirstVerse()
Hey, ho, the wind and the rain
###

If we had tried this import with testmain1.py, the main() function would
fire off immediately:

###
>>> import testmain1
Hey, ho, the wind and the rain
For the rain, it raineth every day
###


Good luck to you!