[Tutor] main

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Nov 6 02:42:31 CET 2005



On Sat, 5 Nov 2005, Shi Mu wrote:

> It is very hard for me to understand why we need the following line? if
> __name__ == "__main__":


Hi Shi Mu,

It's tied to the concept of modules.  Have you learned about modules yet?

Python programs can be split into several modular pieces, and these
"modules" live in text files.  You may have seen some prewritten modules
already in the Standard Library:

    http://www.python.org/doc/lib/

These modules are physically no different than the programs you've already
written:  they live in text files just like others.


The 'if __name__ == "__main__":  ..." trick exists in Python so that our
Python files can act as either reusable modules, or as standalone
programs.  As a toy example, let's say that we have two files:

######
mumak:~ dyoo$ cat mymath.py
def square(x):
    return x * x

if __name__ == '__main__':
    print "test: square(42) ==", square(42)


mumak:~ dyoo$ cat mygame.py
import mymath

print "this is mygame."
print mymath.square(17)
######

In this example, we've written mymath.py to be both used as a utility
module, as well as a standalone program.  We can run mymath standalone by
doing this:

######
mumak:~ dyoo$ python mymath.py
test: square(42) == 1764
######


But we can also use mymath.py as a module; let's see what happens when we
run mygame.py:

######
mumak:~ dyoo$ python mygame.py
this is mygame.
289
######

Notice that here we don't see the 'test' line that mymath.py had near the
bottom of its code.  That's because, in this context, mymath is not the
main program.  That's what the 'if __name__ == "__main__": ...' trick is
used for.

(Another mainstream programming language that does a simliar trick is
Java: each Java class can define a "main" function that gets executed if
we use that class as our entry point.)


Does this make sense?  Please feel free to ask more questions about this.



More information about the Tutor mailing list