[Tutor] Questions about Functions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Feb 18 16:45:01 2003


> do you ever need to consider having this kind of thing:
>
> >
> > if __name__ =3D=3D =93__main__=94: main()
>
> Only if you ever want to test the program as a stand-alone thing...i.e.
> before it is ever imported into anything.

Hi everyone,


Another reason we might want to put that line,

    if __name__ =3D=3D "__main__": main()

at the bottom of the file is because it gives us freedom to move around
the actual "main" function definition anywhere we want, even to the top.
That is, it allows us doing something like:

###
import time

def main():
    print "What is today?"
    print getTime()

def getTime():
    print time.strftime("%Y-%M-%d")


if __name__ =3D=3D '__main__':
    main()
###



If we didn't have that "if __name__ =3D=3D '__main__'..." part, then we'll =
be
forced by timing / variable binding issues to delay writing out our main()
until the end, until all the dependent functions are defined and known:

###
import time

def getTime():
    print time.strftime("%Y-%M-%d")

print "What is today?"
print getTime()
###


This second version is slightly shorter, but is less versatile: now that
we've exposed our main program outside of a function, we now don't have
much freedom to move the main function to the top of our file.


That is, if we tried doing:

###  ## buggy code
import time

print "What is today?"
print getTime()


def getTime():
    print time.strftime("%Y-%M-%d")
###

Python will give an error, because by the time we get to the fourth line
or so, it still doesn't know about getTime() yet--- it has no idea that
the getTime() definition is coming up, because it hasn't read that far
yet.


So using "'if __name__ =3D=3D '__main__'" isn't just for making it easier t=
o
run tests (although it's a major reason.)  But another reason is because
it lets us organize our main code, so that we're more free to move things
around.


Hope that helps!